#!/bin/bash
#
# Copyright 2014-2023 Security Onion Solutions, LLC
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

. /usr/sbin/so-common

usage() {
    echo "Usage: $0 <user-email>"
    echo ""
    echo "Deletes a user in Fleet"
    exit 1
}

if [ $# -ne 1 ]; then
  usage
fi

USER_EMAIL=$1
FLEET_SA_EMAIL=$(lookup_pillar_secret fleet_sa_email)
FLEET_SA_PW=$(lookup_pillar_secret fleet_sa_password)

# Config fleetctl & login with the SO Service Account
CONFIG_OUTPUT=$(docker exec so-fleet fleetctl config set --address https://127.0.0.1:8080 --tls-skip-verify --url-prefix /fleet  2>&1 )
SALOGIN_OUTPUT=$(docker exec so-fleet fleetctl login --email $FLEET_SA_EMAIL --password $FLEET_SA_PW 2>&1)

if [[ $? -ne 0 ]]; then
    echo "Unable to delete user from Fleet; Fleet Service account login failed"
    echo "$SALOGIN_OUTPUT"
    exit 2
fi

# Delete User
DELETE_OUTPUT=$(docker exec so-fleet fleetctl user delete --email $USER_EMAIL 2>&1)

if [[ $? -eq 0 ]]; then
    echo "Successfully deleted user from Fleet"
else
    echo "Unable to delete user from Fleet"
    echo "$DELETE_OUTPUT"
    exit 2
fi


