#!/bin/bash
# AUTHOR    :   vinci
# DATE      :   2021-01-23_18:44:26
# PROGRAM   :   muninstall
# USAGE     :   muninstall <TARGET>
#
# NEEDS     :
#
# PROVIDES  :
#
# PURPOSE:
#
# EXAMPLE:
#
# NOTES:
#

#=========================
# Exit Codes:
# It's a good style to document your exit codes here.
#-# 100 : No option or argument specified
#-# 101 : Unknown option specified
#-# 102 : Wrong option combination
#-# 103 : Wrong or invalid input
#=========================

#=========================
# MY STANDARD COLORS
# Some take the colb/colf input, some the setaf/setab type of writing
# See what supports your system, comment the rest.
bold=$(tput bold)
reset_all=$(tput sgr0 )

black_on_red=$(     tput setaf 0; tput setab 1)
black_on_green=$(   tput setaf 0; tput setab 2)
black_on_yellow=$(  tput setaf 0; tput setab 3)

red_on_white=$(     tput setaf 1; tput setab 7)
green_on_white=$(   tput setaf 2; tput setab 7)
yellow_on_white=$(  tput setaf 3; tput setab 7)
blue_on_white=$(    tput setaf 4; tput setab 7)

red_on_black=$(     tput setaf 1; tput setab 0)
green_on_black=$(   tput setaf 2; tput setab 0)
yellow_on_black=$(  tput setaf 3; tput setab 0)

red=$(      tput setaf 1)
green=$(    tput setaf 2)
yellow=$(   tput setaf 3)
blue=$(     tput setaf 4)
magenta=$(  tput setaf 5)
cyan=$(     tput setaf 6)
#
# MY STANDARD COLORS END
#=========================

#=========================
# MY VARIABLES BEGIN
# Take this for welcome and log actions.
me=$( whoami | awk '{print $1}' )
my_gecos=$( awk -F":" -v me=$me '$1 == me {print $5}' /etc/passwd )

# If we have no gecos (probably because we have LDAP), take username instead.
if [[ -z $my_gecos ]]; then
    my_gecos=$me
fi

# Initial script infos
version='1.0'
state='productive'
author='Vincenzo Daniele, asteras consulting GmbH'
script_desc="$( basename $0 ), version $version, state $state, author $author ."

# Form welcome string.
separator="=================================================="
script_header="$separator\n Welcome $my_gecos,\n This is $script_desc \n$separator"

# Some colored output markers, 8 chars in length each ...
_ER="${black_on_red}ERROR  :${reset_all}"
_IN="${blue_on_white}INFO   :${reset_all}"
_WA="${black_on_yellow}WARNING:${reset_all}"
_OK="${black_on_green}OK     :${reset_all}"
_DB="${green_on_white}DEBUG  :${reset_all}"
_OE="${black_on_green}OK.${reset_all}"      # Ok at end of line.
# MY VARIABLES END
#=========================


usage()
{
echo -e "
------------------------------------------------------------------------------------
${bold}$(basename $0):${reset_all}

Uninstall MARS client from MARS Master.

${bold}Synopsis :

$(basename $0) [-OPTIONS] TARGET

OPTIONS:${reset_all}
-r                  : Removes host data.
-C                  : Turn off colors.
-d                  : Turn debug mode on.
-h                  : This usage.
-q                  : quiet output.
-v                  : verbose output.
-V                  : Print version and exit.

TARGET              : Target to remove MARS minion.
------------------------------------------------------------------------------------ "
}

#=========================
# OPTION HANDLING BEGIN
while getopts rCdhqvV option
do
    case $option in
        r)  # Remove host data
            flag_remove="up"
        ;;

        C)  # NO Colors
            # Disable standard colors
            bold=""
            reset_all=""
            black_on_red=""
            black_on_green=""
            black_on_yellow=""

            red_on_white=""
            green_on_white=""
            yellow_on_white=""
            blue_on_white=""

            red_on_black=""
            green_on_black=""
            yellow_on_black=""

            red=""
            green=""
            yellow=""
            blue=""
            magenta=""
            cyan=""

            _ER="ERROR  :"
            _IN="INFO   :"
            _WA="WARNING:"
            _OK="OK     :"
            _DB="DEBUG  :"
            _OE="OK."
        ;;

        d)  # Turn debug on
            flag_debug="up"
        ;;

        h) # Help
            usage
            exit 0
        ;;

        q)  # turn on quiet mode
            flag_quiet="up"
        ;;

        v)  # turn on verbose mode
            flag_verbose="up"
        ;;

        V) # version
            echo -e "${bold}\n $script_desc ${reset_all}"
            echo -e "\n Maybe try $(basename $0) -h or man $(basename $0)"
            echo -e " for more information."
            exit 0
        ;;

        *) # Else unknown option
            usage
            exit 101
        ;;
    esac
done
shift $(($OPTIND -1))

#-------------------------
# Get target and fqdn of it.
TARGET=$1
if [[ -z $TARGET ]]; then
    usage
    exit 1
fi

LTARGET=( /usr/local/bin/longname $TARGET )
if [[ -z $LTARGET ]]; then
    echo "$_ER: Could not get long name of $TARGET."
    echo "$_IN : Please retry with FQDN of $TARGET."
    exit 1
fi

# As TARGET might come in as SHORT.SOMETHING, be sure SHORT is really SHORT.
TARGET=$( echo "$LTARGET" | cut -d . -f1 )

SSH=$( which ssh )
if [[ $? -ne 0 ]]; then
    echo "$_ER: No ssh found"
    exit 1
fi

SCP=$( which scp )
if [[ $? -ne 0 ]]; then
    echo "$_ER: No scp found"
    exit 1
fi

$SSH $LTARGET /usr/local/sbin/marsconfigure_minion disable

$SCP /usr/local/sbin/minstall_helper.py ${LTARGET}:/tmp

python3=$( $SSH $LTARGET which python3 )
if [[ $? -eq 0 ]]; then
    $SSH $LTARGET $python3 /tmp/minstall_helper.py uninstall=true
else
    $SSH $LTARGET python /tmp/minstall_helper.py uninstall=true
fi
$SSH $LTARGET rm -f /tmp/minstall_helper.py

if [[ ! -z $( salt-key -L | awk '$1 == "'$LTARGET'"' ) ]]; then
    salt-key -yd $LTARGET
fi

if [[ -d /opt/marsmaster/hosts/$TARGET ]]; then
    if [[ $flag_remove == "up" ]]; then
        echo "$_IN: Removing /opt/marsmaster/hosts/$TARGET"
        rm -rf /opt/marsmaster/hosts/$TARGET
    else
        mv /opt/marsmaster/hosts/$TARGET /opt/marsmaster/hosts/removed_$TARGET
        echo "$_IN: Moved /opt/marsmaster/hosts/$TARGET => /opt/marsmaster/hosts/removed_$TARGET"
    fi
fi