#! /bin/bash

UpdateIp=$1

read -s -p "please input Rollback password:" updateNP
echo -e "\n"
updateNP=$(perl -e 'print quotemeta shift(@ARGV)' "${updateNP}")

if [ -f /tmp/fiupdate/rollbackfiupdate.log ]
then
    mv /tmp/fiupdate/rollbackfiupdate.log /tmp/fiupdate/rollbackfiupdate_old.log > /dev/null 2>&1
fi
fiUPLog=/tmp/fiupdate/rollbackfiupdate.log
mkdir -p /tmp/fiupdate
touch $fiUPLog
chown -R ossadm:ossgroup /tmp/fiupdate

function get_cur_path()
{
    dir=`/usr/bin/dirname $0`
    ispoint=`/bin/echo $dir| /usr/bin/awk -F/ '{print $1}'`
    if [ "$ispoint" = "." ]
    then
        dir=`/bin/echo $dir|/usr/bin/sed 's/^.//'`
        curpath="`pwd`$dir"
    elif [ "$ispoint" = ".." ]
    then
        curpath="`pwd`/$dir"
    else
       curpath="$dir"
    fi

    return 0
}

get_cur_path
cd "${curpath}"

rollback()
{

    py=${curpath}/../py_work/rollbackfiupdate.pyc
    if [ -f ${curpath}/../py_work/rollbackfiupdate.py ]
    then
        py=${curpath}/../py_work/rollbackfiupdate.py
    fi
    pyCmd=/opt/fiupdate/ODAESwiftDeployPlugin/ODAEDeployTool/rtsp/python/bin/python
    expect <<END
        set timeout -1
        spawn ${pyCmd} ${py}
        expect {
            "*assword:" {send "$updateNP\r"}
        }
        expect eof
END

    firesult=`tail $fiUPLog`
    if [[ $firesult =~ "FI Rollback success" ]]
    then
        echo "[`date '+%Y-%m-%d %H:%M:%S'`] ${UpdateIp} FI Rollback success " >> $fiUPLog
        return 0
    else
        if [[ $firesult =~ "FI Rollback failed" ]]
        then
            echo "[`date '+%Y-%m-%d %H:%M:%S'`] ${UpdateIp} FI Rollback failed " >> $fiUPLog
            return 1
        fi
        # 如果回滚失败，执行二次检查，防止出现无法登录update service但实际回滚成功的情况
        exc_check_update_status
        if [ $? -eq 0 ]
        then
            echo "[`date '+%Y-%m-%d %H:%M:%S'`] ${UpdateIp} FI Rollback success " >> $fiUPLog
            return 0
        else
            echo "[`date '+%Y-%m-%d %H:%M:%S'`] ${UpdateIp} FI Rollback failed " >> $fiUPLog
            return 1
        fi

    fi
}

exc_check_update_status()
{
    task_id=`cat /opt/huawei/Bigdata/update-service/data/task.id`
    projects_file=`grep -w ${task_id} -nr /opt/huawei/Bigdata/update-service/data/ | grep projects_status.json | awk -F':' '{print $1}'`
    
    if [ -f /opt/huawei/Bigdata/update-service/data/task.id -a -f "$projects_file" ]
    then
        for ((i=1;i<=1800;i++))
        do
            sleep 5
            check_update_status
            result_status=$?
            if [ $result_status -eq 2 ]
            then
                continue
            fi
            if [ $result_status -eq 1 ]
            then
                return 1
            fi
            if [ $result_status -eq 0 ]
            then
                return 0
            fi
        done
    fi

    return 1
}

check_update_status()
{
    currentTask=$(/opt/fiupdate/ODAESwiftDeployPlugin/ODAEDeployTool/rtsp/python/bin/python -c "import json
with open(\""${projects_file}"\", 'r') as f_obj:
    plandata_content = json.load(f_obj)
    output_data = plandata_content
    print(output_data.get('currentTask'))")
    
    rollback_status=$(/opt/fiupdate/ODAESwiftDeployPlugin/ODAEDeployTool/rtsp/python/bin/python -c "import json
with open(\""${projects_file}"\", 'r') as f_obj:
    plandata_content = json.load(f_obj)
    output_data = plandata_content
    print(output_data.get('projectStatuses').get('ROLLBACK').get('status'))")
    
    rollback_process=$(/opt/fiupdate/ODAESwiftDeployPlugin/ODAEDeployTool/rtsp/python/bin/python -c "import json
with open(\""${projects_file}"\", 'r') as f_obj:
    plandata_content = json.load(f_obj)
    output_data = plandata_content
    print(output_data.get('projectStatuses').get('ROLLBACK').get('progress'))")

    if [[ "$currentTask" =~ "ROLLBACK" ]]
    then
        # 回滚成功，进度100
        if [ "$rollback_status" == "SUCCEED" -a "$rollback_process" == "100" ];then
            return 0
        fi
        # 回滚失败
        if [ "$rollback_status" == "FAILED" -o "$rollback_status" == "failed" -o "$rollback_status" == "Failed" -o "$rollback_status" == "fail" ];then
            return 1
        fi
        echo "[`date '+%Y-%m-%d %H:%M:%S'`] STATUS: FI is updating, stage is Rollback "
        echo "[`date '+%Y-%m-%d %H:%M:%S'`] INFO: FI update start check project stage start:Rollback " >> $fiUPLog
        return 2
    else
        return 1
    fi
}

Main()
{
    rollback
    if [ $? -ne 0 ]
    then
        echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] FI Rollback failed" >> $fiUPLog
        return 1
    fi
    return 0
}

Main $*
exit $?

