#! /bin/bash

UpdateIp=$1

read -s -p "please input update password:" updateNP
echo -e "\n"
updateNP=$(perl -e 'print quotemeta shift(@ARGV)' "${updateNP}")
if [ -f /tmp/fiupdate/fiupdate.log ]
then
    mv /tmp/fiupdate/fiupdate.log /tmp/fiupdate/fiupdate_old.log > /dev/null 2>&1
fi
fiUPLog=/tmp/fiupdate/fiupdate.log
mkdir -p /tmp/fiupdate
touch $fiUPLog
chown -R ossadm:ossgroup /tmp/fiupdate
SysVerInfo=`cat /etc/os-release`
if [[ "$SysVerInfo" =~ "SLES" ]]; then
    echo "[`date '+%Y-%m-%d %H:%M:%S'`] system is SUSE" 
    SysVer="SUSE"
elif [[ "$SysVerInfo" =~ "EulerOS" ]]; then
    echo "[`date '+%Y-%m-%d %H:%M:%S'`] system is EulerOS"
    SysVer="EulerOS"
else
    echo "[`date '+%Y-%m-%d %H:%M:%S'`] system is not SUSE,is not EulerOS"
    echo "[`date '+%Y-%m-%d %H:%M:%S'`] FI cannot install"
    echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] FI update commit failed" >> $fiUPLog
    exit 1
fi

cpu=`uname -a`
if [[ "$cpu" =~ "aarch64" ]]; then
    cpu="ARM"
else
    cpu="x86"
fi

function get_cur_path()
{
    cd "$(dirname "${BASH_SOURCE-$0}")"
    work_curPath="${PWD}"
    fi_scriptName="$(basename "${BASH_SOURCE-$0}")"
    cd - >/dev/null
}

get_cur_path
cd "${work_curPath}"

update()
{

    py=${work_curPath}/../py_work/commit_fiupdate.pyc
    if [ -f ${work_curPath}/../py_work/commit_fiupdate.py ]
    then
        py=${work_curPath}/../py_work/commit_fiupdate.py
    fi
    pyCmd=/opt/fiupdate/ODAESwiftDeployPlugin/ODAEDeployTool/rtsp/python/bin/python
    expect <<END
        set timeout -1
        spawn ${pyCmd} ${py} $UpdateIp "${SysVer}" "$cpu"
        expect {
            "*assword:" {send "$updateNP\r"}
        }
        expect eof
END
    
    firesult=`tail $fiUPLog`
    if [[ $firesult =~ "FI update commit success" ]]
    then
        echo "[`date '+%Y-%m-%d %H:%M:%S'`] ${UpdateIp} FI update commit success"
        echo "\n[`date '+%Y-%m-%d %H:%M:%S'`] ${UpdateIp} FI update commit success " >> $fiUPLog
        return 0
    else
        echo "[`date '+%Y-%m-%d %H:%M:%S'`] ${UpdateIp} FI update commit failed"
        echo "\n[`date '+%Y-%m-%d %H:%M:%S'`] ${UpdateIp} FI update commit failed " >> $fiUPLog
        return 1
    fi
}

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

Main $*
exit $?

