#!/bin/bash


DEFAULT_PREFIX_DIR="/usr/local"
DEFAULT_SUFFIX_DIR="/uniagent"
INSTALL_DIR="${DEFAULT_PREFIX_DIR}${DEFAULT_SUFFIX_DIR}"
UNIAGENT_PROC_NAME="uniagent"

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 isDirectoryEmpty() {
    local directory=$1
    if [[ -z "$(ls -A ${directory})" ]]; then
       # empty
       return 0
    else
       # not empty
       return 1
    fi
}

function main() {
    echo "Start to uninstall ${UNIAGENT_PROC_NAME}..."

    checkExecutor
    getCurrentPath

    INSTALL_DIR="${CURRENT_DIR}/../uniagent"
    cd "$INSTALL_DIR"/bin
    ./${UNIAGENT_PROC_NAME} uninstall-all
    if [[ $? -ne 0 ]]; then
        echo "Uninstall ${UNIAGENT_PROC_NAME} failed and exit(-1)"
        exit -1
    fi

    # remove install(uniagent) directory
    echo "Remove ${INSTALL_DIR} starts"
    rm -rf ${INSTALL_DIR}
    echo "Remove ${INSTALL_DIR} successfully"

    echo "Uninstall ${UNIAGENT_PROC_NAME} in ${INSTALL_DIR} successfully."
    exit 0
}

# start
main
