#!/bin/bash


DEFAULT_PREFIX_DIR="/usr/local"
DEFAULT_SUFFIX_DIR="/uniagent"
INSTALL_DIR="${DEFAULT_PREFIX_DIR}${DEFAULT_SUFFIX_DIR}"
AGENT_NAME_LINUX="uniagent"
UPDATER_NAME_LINUX="updater"
TOOLS_NAME_LINUX="decrypt"

function checkExecutor() {
    if [[ "$(id -u)" = "0" ]]; then
        echo "Current user is root."
    else
        echo "Current user is not root, please use root user install or command [sudo sh install.sh]."
        exit 0
    fi
}

function getCurrentPath() {
    if [[ "` dirname "$0" `" = "" ]] || [[ "` dirname "$0" `" = "." ]] ; then
        CURRENT_DIR=$(dirname $(pwd))
    else
        cd ` dirname "$0" `
        CURRENT_DIR=$(dirname $(pwd))
        cd - > /dev/null 2>&1
    fi
}

# 0: true; 1: false
function isAgentRunning() {
    PIDS=($(pgrep -l -f -P 1,0 "${AGENT_NAME_LINUX}$" | awk '{print $1}'))

    if [[ ${#PIDS[*]} == 1 ]]; then
       # uniagent exists
       return 0
    else
       # uniagent does not exist
       return 1
    fi
}

function checkStatus() {
    isAgentRunning
    status=$?
    if [[ ${status} == 0 ]]; then
        echo "${AGENT_NAME_LINUX} is running, so can't be installed"
        exit 1
    fi
}

function checkPath() {
    if [[ -d ${INSTALL_DIR} ]]; then
        echo "${INSTALL_DIR} has existed already. Please check whether ${AGENT_NAME_LINUX} has been installed."
        exit 1
    fi
}

function getInstallDir() {
    if [[ "$1" && ! -d "$1" ]]; then
        echo "$1" is not a directory! Install ${AGENT_NAME_LINUX} failed.
        exit -1
    fi

    if [[ "$1" && -d "$1" ]]; then
        INSTALL_DIR="$1/${DEFAULT_SUFFIX_DIR}"
    fi
}

function installAndStart() {
    mkdir -p ${INSTALL_DIR}/log
    mv -f ${CURRENT_DIR}/* ${INSTALL_DIR}

    ${INSTALL_DIR}/bin/${AGENT_NAME_LINUX} install
    if [[ $? -eq 0 ]]; then
        echo "${AGENT_NAME_LINUX} install to directory(${INSTALL_DIR}) successfully"
    else
        echo "${AGENT_NAME_LINUX} start failed and exit(-1)"
        exit -1
    fi
}

function cleanTmpDir() {
    rm -rf ${CURRENT_DIR}
}

function configPerm() {
    find ${INSTALL_DIR} -type d -exec chmod 700 {} \;
    find ${INSTALL_DIR} -type f -exec chmod 600 {} \;
    find ${INSTALL_DIR} \( -name ${AGENT_NAME_LINUX} -type f -o -name ${UPDATER_NAME_LINUX} -type f -o -name ${TOOLS_NAME_LINUX} -type f -o -name \*.sh -type f \) -exec chmod 500 {} \;
}

function main() {
    checkExecutor
    checkStatus

    local userDefinedInstallDir=$1
    getInstallDir ${userDefinedInstallDir}


    getCurrentPath
    installAndStart
    configPerm
    cleanTmpDir
}

# main start
main
