#!/bin/bash
declare admin_pwd=''
curPath=""

read -s -p "please input admin password:" admin_pwd
echo -e "\n"

admin_pwd=$(perl -e 'print quotemeta shift(@ARGV)' "${admin_pwd}")

FileName=`basename $0`
OperateLog()
{
    logger -t $USER -p local0.info "${OPERIP:-127.0.0.1}; Execute $FileName, result : $1"
}
GetWorkPath()
{
    dir=`/usr/bin/dirname $0`
    ispointstart=`/bin/echo $dir|/usr/bin/awk -F/ '{print $1}'`
    if [ "$ispointstart" = "." ]
    then
        dir=`/bin/echo $dir|/usr/bin/sed 's/^.//'`
        curPath="`pwd`$dir"
    elif [ "$ispointstart" = ".." ]
    then
        curPath="`pwd`/$dir"
    else
        curPath="$dir"
    fi
    return 0
}
ClearAlarm_upgrade()
{
    cd $curPath/py_work
    script="clear_alarm.pyc"
    if [ -f clear_alarm.py ]
    then
        script="clear_alarm.py"
    fi

    expect <<END
        spawn /opt/ODAEFITool/rtsp/python/bin/python $script $webip 12010,12012,16004,12062,12006
        set timeout 60
        exec sleep 10
        expect {
            "*assword*" {send "$admin_pwd\r"}
            timeout {send_user "No response!\n"
                    exit 1}
        }
        set timeout 1800
        expect eof
        catch wait ret
        set exit_status [lindex \$ret 3]
        exit \$exit_status
END
}

ClearAlarm_rollback()
{
    cd $curPath/py_work
    script="clear_alarm.pyc"
    if [ -f clear_alarm.py ]
    then
        script="clear_alarm.py"
    fi

    expect <<END
        spawn /opt/ODAEFITool/rtsp/python/bin/python $script $webip 43001,14000,16004,12012,12010,12006
        set timeout 60
        exec sleep 10
        expect {
            "*assword*" {send "$admin_pwd\r"}
            timeout {send_user "No response!\n"
                    exit 1}
        }
        set timeout 1800
        expect eof
        catch wait ret
        set exit_status [lindex \$ret 3]
        exit \$exit_status
END
}

Main()
{
    config_name=$1
    webip=$2
    GetWorkPath
 
    if [ "x-$config_name" = "x-upgrade" ]
        then
            ClearAlarm_upgrade
        elif [ "x-$config_name" = "x-rollback" ]
        then
            ClearAlarm_rollback
    fi

    echo "[`date '+%Y-%m-%d %H:%M:%S'`]--Successful."
}

Main $*
ret=$?
if [ $ret -eq 0 ]
then
    OperateLog "success"
else
    OperateLog "failed"
fi
exit $ret

