#! /bin/bash

GetWorkPath()
{
    echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] Precheck work is start."
    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
}

InputParas()
{
    whouser=`whoami`
    if [ "$whouser" != "root" ]
    then
        echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] please run this script as user 'root' "
        exit 1
    fi

}
verify()
{
    rm -rf /opt/fiupdate/log/verifyFIpackges.log > /dev/null 2>&1
    packge_dir="/opt/fiupdate/package"
    packge_all=`find $packge_dir/ -name "FusionInsight*.tar.gz" -type f`
    for packge in ${packge_all}
    do
    {
        /opt/signtool/verifyPkgSign ${packge}  > /dev/null 2>&1
        if [ $? -eq 0 ];then
            echo -e "the packge ${packge} verify Successfully." >>/opt/fiupdate/log/verifyFIpackges.log
        else
            echo -e "the packge ${packge} verify Failed." >>/opt/fiupdate/log/verifyFIpackges.log
        fi
    }
    done
    if [ -f /opt/fiupdate/log/verifyFIpackges.log ]
    then
        verifyresult=`cat /opt/fiupdate/log/verifyFIpackges.log | grep 'verify Failed'`
        if [ -n "$verifyresult" ]
        then
            echo "precheck verify all FI packges is abnormal, please check in /opt/fiupdate/log/verifyFIpackges.log."
            return 1
        else
            echo "precheck verify all FI packges is normal."
        fi
    fi
}

Main()
{
    InputParas
    verify
    echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] \033[42;34m Precheck work verify FI packges is successfully. \033[0m"
    return 0
}

SuperMain()
{
    Main $* > ${curpath}/log/update_fi_pre_verify.log
    ret=$?
    if [ $ret -eq 0 ]
    then
        echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] Precheck work in stage Verifypackges is successfully."
        echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] Precheck work in stage Verifypackges is successfully." >> ${curpath}/log/update_fi_pre_verify.log
    else
        echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] Precheck work in stage Verifypackges is failed."
        echo -e "\n[`date '+%Y-%m-%d %H:%M:%S'`] Precheck work in stage Verifypackges is failed." >> ${curpath}/log/update_fi_pre_verify.log
    fi
    chown -R ossadm:ossgroup ${curpath}/log/
}

GetWorkPath
SuperMain $* &
superret=$?
exit $superret
