#!/bin/bash

RegionID=""
TelescopeDirName="telescope"
HolderTelescope="/usr/local/uniagent/extension/holder/telescope"
TelescopeTempDir="/tmp/ces-uniagent/telescope"
UniagentTempDir="/tmp/ces-uniagent"
CESAgentInstallLock="/tmp/ces_agent_install.lock"
UNIAGENT_PROC_NAME="uniagent"
TELESCOPE_PROC_NAME="telescope"
OBSDomain="myhuaweicloud.com"
KunpengMark=""
KunpengRegionList=("cn-central-202" "cn-east-204" "cn-northwest-204" "cn-north-209" "cn-southwest-204")
NicIP=""
UniagentVersion="0.1.5"
TelescopeVersion="2.5.6"

function downloadPkg() {
    which curl
    if [[ $? -eq 0 ]]; then
          curl -k -o $2 $1
          return 0
    fi

    which wget
    if [[ $? -eq 0 ]]; then
          wget -o $2 $1
          return 0
    fi
    return 1
}

function installUniAgent() {
    UniAgent="uniagent_linux_${Arch}"
    UniAgentPkg="uniagent_linux_${Arch}"
    if [[ -n "${UniagentVersion}" ]]; then
        UniAgentPkg="uniagent_linux_${Arch}_${UniagentVersion}"
    fi
    UniAgentPkg="${UniAgentPkg}.tar.gz"
    UniAgentOBSUrl="https://uniagent-${RegionID}.obs.${RegionID}${KunpengMark}.${OBSDomain}/package/${UniAgentPkg}"
    downloadPkg ${UniAgentOBSUrl} ${UniagentTempDir}/${UniAgentPkg}

    if [[ $? -ne 0 ]]; then echo "Download ${UniAgentOBSUrl} failed and exit(-1)"; exit -1; fi
    tar -zxvf ${UniagentTempDir}/${UniAgentPkg} -C ${UniagentTempDir}
    if [[ $? -ne 0 ]]; then echo "Tar ${UniAgentPkg} failed and exit(-1)"; exit -1; fi
    bash ${UniagentTempDir}/${UniAgent}/script/install.sh -d ${AgentApiDomain}
    if [[ $? -ne 0 ]]; then echo "Install ${UniAgent} failed and exit(-1)"; exit -1; fi
}

function installTelescope() {
    mkdir -p ${TelescopeTempDir}
    mkdir -p ${HolderTelescope}
    chmod 700 ${HolderTelescope} $(dirname ${HolderTelescope})

    Telescope="telescope"
    if [[ -n "${TelescopeVersion}" ]]; then
        Telescope="telescope-${TelescopeVersion}"
    fi
    TelescopePkg="${Telescope}.tar.gz"
    TelescopeOBSUrl="https://uniagent-${RegionID}.obs.${RegionID}${KunpengMark}.${OBSDomain}/extension/telescope/${TelescopePkg}"
    downloadPkg ${TelescopeOBSUrl} ${TelescopeTempDir}/${TelescopePkg}

    if [[ $? -ne 0 ]]; then echo "Download ${TelescopeOBSUrl} failed and exit(-1)"; exit -1; fi
    tar -zxvf ${TelescopeTempDir}/${TelescopePkg} -C ${TelescopeTempDir}
    if [[ $? -ne 0 ]]; then echo "Tar ${TelescopePkg} failed and exit(-1)"; exit -1; fi
    bash ${TelescopeTempDir}/${TelescopeDirName}/linux_${Arch}_bin/install.sh -d ${AgentApiDomain}
    if [[ $? -ne 0 ]]; then echo "Execute install.sh(telescope) failed and exit(-1)"; exit -1; fi
    cp -f ${TelescopeTempDir}/${TelescopeDirName}/manifest.json ${HolderTelescope}/manifest.json
    echo "{\"state\": \"started\"}" > ${HolderTelescope}/state.json
    chmod 600 ${HolderTelescope}/manifest.json ${HolderTelescope}/state.json
}

function isProcessRunning() {
    PROC_NAME=$1
    pgrep -l -f -P 1 "${PROC_NAME}$"

    if [[ $? == 0 ]]; then
       # process exists
       return 0
    else
       # process does not exist
       return 1
    fi
}

function checkStatus() {
    isProcessRunning ${UNIAGENT_PROC_NAME} > /dev/null
    status=$?
    if [[ ${status} == 0 ]]; then
        echo "Upgrading agent to the latest version, please wait..."
        bash /usr/local/uniagent/script/uninstall.sh > /dev/null
        if [[ $? -ne 0 ]]; then echo "${UNIAGENT_PROC_NAME} is running, reinstall ${UNIAGENT_PROC_NAME} failed and exit(-1)"; exit -1; fi
    fi

    isProcessRunning ${TELESCOPE_PROC_NAME}
    status=$?
    if [[ ${status} == 0 ]]; then
        echo "${TELESCOPE_PROC_NAME} is running, so can't be installed."
        echo "Please use \"sh /usr/local/telescope/uninstall.sh\" to uninstall ${TELESCOPE_PROC_NAME} and try to reinstall."
        exit 1
    fi
}

function singleCheck() {
    ## 锁文件不存在，或者锁文件内容中的pid不存在，则认为可以运行
    if [ -e ${CESAgentInstallLock} ] && kill -0 `cat ${CESAgentInstallLock}`; then
        echo "another agent_install.sh is already running, exit."
        exit 1
    fi

    #将当前程序进程id写入锁文件
    PID=$$
    echo "pid: ${PID}"
    echo ${PID} > ${CESAgentInstallLock}

    sleep 1

    PID_LOCK=`cat ${CESAgentInstallLock}`
    echo "pid: ${PID_LOCK} lock"
    if [[ ${PID} != ${PID_LOCK} ]]; then
        echo "lock agent_install.sh failed, exit."
        exit 1
    fi
}

function prepareOsArchType(){
    if [[ $(arch) == "x86_64" ]]; then
        Arch="amd64"
    elif [[ $(arch) == "aarch64" ]]; then
        Arch="arm64"
    else
        Arch="amd64"
    fi
}

function prepareRegionIDAndOBSDomain() {
    meta_data=$(curl -s -m 2 http://169.254.169.254/openstack/latest/meta_data.json)
    region_id=$(echo "${meta_data}" | awk -F"[,:}]" '{for(i=1;i<=NF;i++){if($i~/region_id\042/){print $(i+1)}}}' | tr -d ' "')
    if [[ -z "${RegionID}" ]]; then
        RegionID=$region_id
    fi
    if [[ -z "${RegionID}" ]]; then
        echo "need param RegionID."
        exit 1
    fi

    if [[ ${RegionID} == "cn-north-7" ]]; then
        OBSDomain="ulanqab.huawei.com"
    fi

    for kunpenRegionID in ${KunpengRegionList[@]}
    do
        if [[ ${kunpenRegionID} == ${RegionID} ]]; then
            KunpengMark="-dev"
        fi
    done
}

function setNicIPConfig() {
    if [[ -z "${NicIP}" ]]; then
        return
    fi

    echo "{\"uniagent.http.nic.ip\":\"${NicIP}\"}" > /usr/local/uniagent/conf/custom_conf.json
    service ces-uniagent.service restart

    echo "{\"telescope.http.nic.ip\":\"${NicIP}\"}" > /usr/local/uniagent/extension/install/telescope/conf/custom_conf.json
    /usr/local/uniagent/extension/install/telescope/telescoped restart
}

function help() {
    echo "Usage:"
    echo "agent_install.sh [-r RegionID] [-u UniagentVersion] [-t TelescopeVersion] [-d AgentApiDomain] [-o OBSDomain]"
    exit -1
}

function main() {
    singleCheck

    mkdir -p ${UniagentTempDir}
    mkdir -p ${TelescopeTempDir}
    trap "rm -rf ${UniagentTempDir} ${TelescopeTempDir} ${CESAgentInstallLock}" INT TERM EXIT

    checkStatus

    prepareOsArchType
    prepareRegionIDAndOBSDomain

    installUniAgent
    installTelescope
    
    setNicIPConfig
}

# start
while getopts ':r:u:t:d:o:n:h' OPT; do
    case $OPT in
        r)
            RegionID="$OPTARG";;
        u)
            UniagentVersion="$OPTARG";;
        t)
            TelescopeVersion="$OPTARG";;
        d)
            AgentApiDomain="$OPTARG";;
        o)
            OBSDomain="$OPTARG";;
        n)
            NicIP="$OPTARG";;
        h)
            help;;
    esac
done
main
