#*******************************************************************************
# Copyright (c) 2016-2017 Hewlett Packard Enterprise Development LP.
# Copyright (c) 2014-2015  Hewlett-Packard Development Company, L.P. 
# All rights reserved.
#*******************************************************************************
################################################################################ 
# Options passed to the script
# -c : Configure jetty
#      Jetty configuration involves the following
#      * Modify the xml files in jetty/etc to deploy SGMGR UI and backend 
#      * Configure the jetty-sgmgr-base directory
#      * Start the Jetty Server
# -e : Erase jetty
#      * Stop the Jetty Server
#      * Remove the replicated user(sgmgr)
# -u : Add/modify user based on SGMGR_ENV variable passed
# -m : Configure multicast port. Default is 5301
#
###############################################################################

#!/bin/sh

#Global variables
userOption=""
mcastPortVal=5301
mcastPortSet="FALSE"
osDistroType=""
install_sgmgr_loc=""
install_jetty_loc=""
Option=""
retval=0
username="sgmgr"
setupRetval=0
sgmgr_setup_script=""

. /etc/cmcluster.conf


if [ "$SGROOT" = "/opt/hpe/serviceguard/sgcmcluster" ];then
    install_sgmgr_loc="/opt/hpe/serviceguard/sgmgr"
elif [ "$SGROOT" = "/usr/local/cmcluster" ];then
    install_sgmgr_loc="/opt/hp/cmcluster/serviceguardmanager"
    usr_local="/usr/local"
elif [ "$SGROOT" = "/opt/cmcluster" ]; then
    install_sgmgr_loc="/opt/hp/cmcluster/serviceguardmanager"
    usr_local="/usr/local"
else
    echo "ERROR: Serviceguard Manager UI cannot install in unknown location"
    exit 1;
fi

sgmgr_setup_script=$install_sgmgr_loc/Serviceguard_manager_setup
#source serviceguard manager utils 
if [  -f $install_sgmgr_loc/sgmgr_setup_utils.sh ]; then
    . $install_sgmgr_loc/sgmgr_setup_utils.sh
else
    echo  "ERROR($sgmgr_setup_script_loc): Unable to source utils"
    exit 1;
fi

usage() {
    echo -e "\n\t Usage: $0 -c|-e [-u]";
    echo -e "\n\t NOTE:  ";
    echo -e "\n\t\t *) Use -c and -u  \t\t if you want to create sgmgr user locally on the node. Before running above command with -u option, 
             \n\t\t                   \t\t please mention the password using export SGMGR_ENV=<password> command.";
    echo -e "\n\t\t *) Use -e and -u \t\t if you want user sgmgr to be deleted"
    echo -e "\n\t\t *) Do not use [-u] \t\t if you are planning to use sgmgr account created in LDAP Server."; 1>&2; 
    exit 1;
}

while getopts ":m:huec" optval; do
    case "${optval}" in
        u) userOption="TRUE"
               ;;
        e) log_msg "Erasing Jetty Configuration....." 
           Option="erase"
               ;;
        h) usage
               ;;
        m) mcastPortVal="$OPTARG"
           mcastPortSet="TRUE"
               ;;
        c) log_msg "Configuring Bundled Jetty....."
           Option="configure"
               ;;
        :) log_msg "Option -$OPTARG requires an argument." 
               ;;
        *) log_msg "Invalid option $1"
           usage
               ;;
    esac
done

if [ "$Option" != "erase" ]  && [ "$Option" != "configure" ]; then
    usage
fi
install_jetty_loc=$install_sgmgr_loc/jetty
osDistroType=$(getOSDistroType);
if [ "$osDistroType" = "DEBIAN" ]; then
    # initialize variable specific to debian distro
    username="stack"
fi

append_ini_file="$install_sgmgr_loc/start.ini"
location_txt="$install_sgmgr_loc/jetty_location.txt"
jettyRunningStatus=0
jettyCmdString=""
 
if [ "$Option" = "configure" ]
then
    if [ "$userOption" = "TRUE" ]; then
        sgmgr_add_user $SGMGR_ENV
    fi
    #check if the jetty-sgmgr service is running
    if isJettySystemctlRequired; then
        jetty_systemctl_out=$(systemctl list-units | grep jetty-sgmgr || true)
        #check if the jetty-sgmgr service is running
        jetty_service_status=$(echo "$jetty_systemctl_out" | awk '{print $4}' || true)
        if [ ! -z "$jetty_service_status" ] && [ "$jetty_service_status" = "running" ];then
            log_msg " Stopping Serviceguard Manager Jetty Server ....."
            systemctl stop jetty-sgmgr || jettyRunningStatus=$?
            jettyCmdString="systemctl stop jetty-sgmgr"
        fi
    else
        jettyPid=$(service jetty-sgmgr status | grep "Jetty running pid=" | awk -F"=" '{print $2}' || true)
        if [ ! -z "$jettyPid" ]; then
            log_msg "Stopping Serviceguard Manager Jetty Server ....."
            service jetty-sgmgr stop >> $install_jetty_loc/logs/jetty_start_stop.log 2>&1 || jettyRunningStatus=$?
            jettyCmdString="service jetty-sgmgr stop"
        fi
    fi
    if [ $jettyRunningStatus -ne 0 ]; then
        echo "ERROR: Unable to stop the Serviceguard manager Jetty instance."
        echo "       Use $jettyCmdString to stop the Serviceguard "
        echo "       Manager Jetty instance manually."
        exit 1;
    fi 

    if ! isDebianDistro  && [ "$mcastPortSet" = "TRUE" ]; then
        updateMulticastPort $install_sgmgr_loc $mcastPortVal || updateRetval="$?"
    fi
    
    sgmgr_setup_config || setupRetval="$?"
    if [ "$setupRetval" = "0" ];then
        setupRetval="$updateRetval"
    fi

    log_msg "Starting Jetty Server ....."
    if isJettySystemctlRequired; then
        systemctl daemon-reload
        systemctl start jetty-sgmgr
    else 
        service jetty-sgmgr start >> $install_jetty_loc/logs/jetty_start_stop.log 2>&1 
    fi

    log_msg " The Jetty log file can be found in $install_jetty_loc/logs/jetty_start_stop.log "
      
    vIBM=`java -version 2>&1 | grep "IBM"`
    if [ ! -z "$vIBM" ];then
        checkSGMgrUIForIBM $install_sgmgr_loc
    fi  
        

elif [ "$Option" = "erase" ]
then
    if [ "$userOption" = "TRUE" ]; then
        removeUser="y" 
    fi
    if isJettySystemctlRequired; then
        jetty_systemctl_out=$(systemctl list-units | grep jetty-sgmgr || true)
        #check if the jetty-sgmgr service is running
        jetty_service_status=$(echo "$jetty_systemctl_out" | awk '{print $4}' || true)
        if [ ! -z "$jetty_service_status" ] && [ "$jetty_service_status" = "running" ];then
            log_msg "Stopping Serviceguard Manager Jetty Server ....."
            systemctl stop jetty-sgmgr || jettyRunningStatus=$?
            jettyCmdString="systemctl stop jetty-sgmgr"
        fi
    else
        jettyPid=$(service jetty-sgmgr status | grep "Jetty running pid=" | awk -F"=" '{print $2}' || true)
        if [ ! -z "$jettyPid" ]; then
            log_msg "Stopping Serviceguard Manager Jetty Server ....."
            service jetty-sgmgr stop >> $install_jetty_loc/logs/jetty_start_stop.log 2>&1 || jettyRunningStatus=$?
            jettyCmdString="service jetty-sgmgr stop"
        fi
    fi
    if [ $jettyRunningStatus -ne 0 ]; then
        echo "ERROR: Unable to stop the Serviceguard manager Jetty instance."
        echo "       Use $jettyCmdString to stop the Serviceguard "
        echo "       Manager Jetty instance manually."
        exit 1;
    fi 
    sgmgr_setup_erase $removeUser || setupRetVal="$?"

else
    log_msg "Wrong parameter $Option"
    exit 2
fi
exit $setupRetval
