#! /bin/bash
log_file="rollback_config_runtime.sh.log"

GetWorkPath()
{
    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
    
    mkdir -p $curpath/log
    touch $curpath/log/$log_file
    
    return 0
}

Main()
{
    GetWorkPath
    echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] begin fix rollback config runtime..." >> $curpath/log/$log_file
    #check if RollbackOMServer failed
    if [ ! -f /opt/huawei/Bigdata/update-service/data/*/result/Rollback/RollbackOMServer.rst ]
    then
        echo "[`date '+%Y-%m-%d %H:%M:%S'`]RollbackOMServer.rst not exists, do not config." >> $curpath/log/$log_file
        return 0
    fi
    RollbackOMServer=/opt/huawei/Bigdata/update-service/data/*/result/Rollback/RollbackOMServer.rst
    taskid=`echo $RollbackOMServer | awk -F "/" {'print $7'}`
    node_state=`cat $RollbackOMServer | grep "NODE_STATE_FAIL"`
    if [ ! -n "$node_state" ]
    then
        echo "RollbackOMServer does not fail, do nothing." >> $curpath/log/$log_file
        return 0
    fi
    #if IP single mode
    cur_scene=`cat /opt/fiupdate/NCE_info/nodes_${product_name}.ini | grep 'IP_SINGLE'`
    if [ $? -eq 0 ]
    then
        echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] begin fix rollback config runtime to rollback FusionInsight..." >> $curpath/log/$log_file
        mkdir -p /tmp/runtime0KeyBak >/dev/null 2>&1
        mv /opt/huawei/Bigdata/common/runtime0/security/rk3d/k3 /tmp/runtime0KeyBak
        mv /opt/huawei/Bigdata/common/runtime0/security/rkp/rk2 /tmp/runtime0KeyBak
        mv /opt/huawei/Bigdata/common/runtime0/security/rp/rkc1 /tmp/runtime0KeyBak
        cp /opt/huawei/Bigdata/common/runtime1/security/rk3d/k3 /opt/huawei/Bigdata/common/runtime0/security/rk3d/ >/dev/null 2>&1
        cp /opt/huawei/Bigdata/common/runtime1/security/rkp/rk2 /opt/huawei/Bigdata/common/runtime0/security/rkp/ >/dev/null 2>&1
        cp /opt/huawei/Bigdata/common/runtime1/security/rp/rkc1 /opt/huawei/Bigdata/common/runtime0/security/rp/ >/dev/null 2>&1
        chown -R omm:wheel /opt/huawei/Bigdata/common/runtime0/security >/dev/null 2>&1
    fi

    return 0
}

Main $*
ret=$?
if [ $ret -eq 0 ]
then
    echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] fix rollback config runtime successfully."
    echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] fix rollback config runtime successfully." >> $curpath/log/$log_file
else
    echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] fix rollback config runtime failed."
    echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] fix rollback config runtime failed." >> $curpath/log/$log_file
fi
exit $ret
