#!/usr/bin/env bash
#description: Agent server

basePath=$(cd `dirname $0`/; pwd)
baseDirPath="${basePath}"
serviceName=$(basename ${basePath})
serviceNameFull=${serviceName}".service"
serviceRegisterAddr="/etc/systemd/system"

uniqueId="9d2b53e"
packageName=$(basename `find ${basePath}/*.jar`)

function ckenv()
{
 echo "Check if net-tools,curl,jdk installed..."
 if ! type netstat >/dev/null 2>&1;then
         echo "net-tools uninstalled, install failed. Please install net-tools first."
         exit 1;
 fi
 if ! type curl >/dev/null 2>&1;then
         echo "curl uninstalled, install failed. Please install curl first."
         exit 1;
 fi
 if ! type java >/dev/null 2>&1;then
         echo "JDK uninstalled, install failed. Please install OpenJDK first."
         exit 1;
 fi
 echo "Environment check successfully, continue to install agent."
}

function gipas()
{
username=${USER}
echo -e "\nPlease type username:"
printf "Use current user by default \e[33m${username}\e[0m, please type operation user: "
read usernametmp

if [[ -n "${usernametmp}" ]]; then
        username=${usernametmp}
        if [[ $(getent passwd ${username}) ]];then
                username=${usernametmp}
		echo export username${serviceName}=${username} >> /etc/profile
        else
                printf "\e[33mWARNING!!! User not found! \e[0m\n"
		exit 1
        fi
fi
}

function install()
{
    if [[ -f ${serviceRegisterAddr}/${serviceNameFull} ]]
    then
        echo "The service has been registered, please do not repeat the installation."
    else
        if grep -q ${serviceName} /etc/profile
        then
           echo "The environment variable already exists."
        else
            ckenv
	          gipas
            echo export ${serviceName}=${baseDirPath} >> /etc/profile
            cat >${serviceRegisterAddr}/${serviceName}.service <<EOF
[Unit]
Description="agent-cloud-servie"
After=network.target
[Service]

Type=oneshot
RemainAfterExit=yes
ExecStart=/usr/sbin/runuser -l ${username} -c  '${baseDirPath}/cloudBridge.sh start'
ExecReload=/usr/sbin/runuser -l ${username} -c  '${baseDirPath}/cloudBridge.sh restart'
ExecStop=/usr/sbin/runuser -l ${username} -c  ${baseDirPath}/cloudBridge.sh stop


[Install]
WantedBy=multi-user.target
EOF
            cd ${serviceRegisterAddr}
            if [[ $? -eq 0 ]]
            then
                chmod 754 ${serviceRegisterAddr}/${serviceName}.service
                systemctl daemon-reload
                if [[ $? -eq 0 ]]
                then
                    systemctl enable ${serviceName}.service
                    addCheck
                    systemctl start ${serviceName}
                    echo "The Agent service installed successfully, need to reboot will take effect, Service Management Method: systemctl start|stop|restart ${serviceNameFull}"
                    return 0
                fi
            fi
            echo "The Agent service installed fail."
        fi
    fi
}

function uninstall()
{
    if [[ ! -f ${serviceRegisterAddr}/${serviceNameFull} ]]
    then
        echo "Agent registration information not found."
    else
        sed -i_bak "/^export ${serviceName}/d" /etc/profile
        if [[ $? -eq 0 ]]
        then
            systemctl disable ${serviceNameFull}
            if [[ $? -eq 0 ]]
            then
                systemctl stop ${serviceNameFull}
                if [[ $? -eq 0 ]]
                then
                    rm ${serviceRegisterAddr}/${serviceNameFull}
                    if [[ $? -eq 0 ]]
                    then
                        deleteCheck
                        echo "uninstall Agent Success."
                        return 0
                    fi
                fi
            fi
        fi
        echo "uninstall Agent fail."
    fi
}

function addCheck()
{
	  echo "*/1 * * * * ${baseDirPath}/cloudBridge.sh check" >> /var/spool/cron/${username}
	  if [[ $? -eq 0 ]]
	  then
	      echo "install watchDog success"
	  else
        echo "install watchDog fail"
    fi
    echo "0 1 * * * ${baseDirPath}/cloudBridge.sh deleteWatchLog" >> /var/spool/cron/${username}
}





function deleteCheck()
{
    usernameFull=username${serviceName}
    usernameValue=`eval echo '$'"${usernameFull}"`
    echo 'usernameFull='${usernameFull}',usernameValue='${usernameValue}
	  tempDeleteDir=`echo ${baseDirPath} | sed 's#\/#\\\/#g'`
    sed -i "/${tempDeleteDir}\/cloudBridge.sh/d"  /var/spool/cron/${usernameValue}
	  if [[ $? -eq 0 ]]
	  then
	      sed -i "/^export ${usernameFull}/d" /etc/profile
	      echo "uninstall watchDog success"
	  else
        echo "uninstall watchDog fail"
    fi
}


if [[ ${#} -ge 1 ]]
then
    case ${1} in
        "install")
            install
        ;;
        "uninstall")
            uninstall
        ;;
         "addCheck")
            addCheck
        ;;
          "deleteCheck")
            deleteCheck
        ;;
          "ckenv")
            ckenv
        ;;
        *)
            echo "${1} No operation"
        ;;
    esac
else
    echo "
    command: install/uninstall/ckenv

    command example: ./agent install
    "
fi
