#!/bin/bash

##################################################
# 获取脚本工作路径和脚本名
##################################################
SCRIPT_PATH=$(cd $(dirname $0);pwd)
SELF_FILE=$(basename $0)
ENT_UPGRADE_PATH="/opt/insight_upgrade"
ES_UPGRADE_PATH="/opt/upgrade"

##################################################
# 初始化日志路径和日志文件名
##################################################
LOG_PATH="/opt/upgrade/easysuite_upgrade/logs"
LOG_FILE="${LOG_PATH}/${SELF_FILE//.sh/}.log"


main()
{
    # 加载公共方法
    . ${SCRIPT_PATH}/common_root.inc
    LOG "INFO" "Start to init log."
    pkgname=$(cd /opt/upgrade;ls *_EntTools_*.zip)
    omp_pkgname="${2}"
    omp_dir="${omp_pkgname%.*}"
    taskid="${4}"
    task_id_path="/opt/upgrade/easysuite_upgrade/taskmgr/${taskid}"
    init_taskmgr ${taskid}
    upgrade_log "INFO" "$*"
    #判断EntTool包是否存在
    if [ -z ${pkgname} ]
    then
        upgrade_log "ERROR" "please check ${pkgname} in /opt/upgrade"
        su - ossadm -c "echo Progress=100 >/opt/upgrade/easysuite_upgrade/taskmgr/${taskid}/task.progress"
        su - ossadm -c "echo Status=fail >/opt/upgrade/easysuite_upgrade/taskmgr/${taskid}/task.status"
        return 1
    fi
    #判断产品升级目录是否存在
    if [ ! -d ${ENT_UPGRADE_PATH} ]
    then
        mkdir -p ${ENT_UPGRADE_PATH}
    fi
    #清理上次的记录
    rm -rf ${ENT_UPGRADE_PATH}/*
    #解压EntTool到产品升级目录
    unzip ${ES_UPGRADE_PATH}/${pkgname} -d ${ENT_UPGRADE_PATH}
    if [ "$?" != "0" ]
    then
        upgrade_log "ERROR" "unzip ${pkgname} to ${ENT_UPGRADE_PATH}"
        su - ossadm -c "echo Progress=100 >/opt/upgrade/easysuite_upgrade/taskmgr/${taskid}/task.progress"
        su - ossadm -c "echo Status=fail >/opt/upgrade/easysuite_upgrade/taskmgr/${taskid}/task.status"
        return 1
    fi
    #解压python
    python_zip=$(ls ${ENT_UPGRADE_PATH}/script/python*.zip)
    if [ -z ${python_zip} ]
    then
        upgrade_log "ERROR" "check python*.zip in /opt/insight_upgrade/script/"
        su - ossadm -c "echo Progress=100 >/opt/upgrade/easysuite_upgrade/taskmgr/${taskid}/task.progress"
        su - ossadm -c "echo Status=fail >/opt/upgrade/easysuite_upgrade/taskmgr/${taskid}/task.status"
        return 1
    fi
    unzip ${python_zip} -d ${ENT_UPGRADE_PATH}/script/python
    if [ "$?" != "0" ]
    then
        upgrade_log "ERROR" "unzip ${python_zip} to /opt/insight_upgrade/script/"
        su - ossadm -c "echo Progress=100 >/opt/upgrade/easysuite_upgrade/taskmgr/${taskid}/task.progress"
        su - ossadm -c "echo Status=fail >/opt/upgrade/easysuite_upgrade/taskmgr/${taskid}/task.status"
        return 1
    fi

    su - ossadm -c "echo Progress=100 >/opt/upgrade/easysuite_upgrade/taskmgr/${taskid}/task.progress"
    su - ossadm -c "echo Status=finish >/opt/upgrade/easysuite_upgrade/taskmgr/${taskid}/task.status"
    upgrade_log "INFO" "unzip ${pkgname} to ${ENT_UPGRADE_PATH} success"
    return 0
}

main "$@"
exit $?