#!/bin/bash

. /etc/functions

run_bin()
{
    bin=
    param=
    factory_default=

    while [ "x$1" != "x" ]
    do
        case $1 in
            *.bin)
                BIN_NAME=`echo $1 | sed "s#.*/\(.*\)#\1#"`
                abs=`echo $1 | cut -c 1`
                if [ "$abs" = "/" ]; then
                    bin=$1
                else
                    bin=`pwd`/$1
                fi
                ;;
            upgrade01)
                param="$param $1"
                ;;
            upgrade02)
                param="$param $1"
                ;;
            factory-default)
                param="$param $1"
                ;;
            no-md5-check)
                ;;
            *)
                echo "invalid option -- '$1'"
                exit 1
                ;;
        esac
        shift 1
    done

    if [ ! -e "$bin" ]; then
        echo "Error: $bin not found!"
        exit 1
    fi

    # check md5
    #if [ -f $bin.md5 ]; then
    #    md5_ok=0
    #    prev_sum=$(md5sum $bin | awk '{print $1}')
    #    while read line
    #    do
    #        file=`echo "$line" | awk '{print $2}' | sed "s#.*/\(.*\)#\1#"`
    #        sum=`echo "$line" | awk '{print $1}'`
    #        if [ "$sum" != "$prev_sum" ] &&  [ "$file" = "$BIN_NAME" ]; then
    #            echo "Error: MD5 mismatched($sum/$pre_sum)!"
    #            exit 1
    #        fi
    #        if [ "$sum" = "$prev_sum" ] &&  [ "$file" = "$BIN_NAME" ]; then
    #            md5_ok=1
    #            break
    #        fi
    #    done < $bin.md5

    #    if [ "$md5_ok" -ne 1 ]; then
    #        echo "Error: MD5 mismatched!"
    #        exit 1
    #    fi
    #fi

    chmod a+x $bin
    $bin $param
    return $?
}

print_help()
{
    echo  "USAGE" 
    echo  "    Upgrade system with local new image"
    echo  "SYNOPSIS"
    echo  "    upgrade [image_name] [no-md5-check] [factory-default]"
    echo  "DESCRIPTION"
    echo  "    image_name(*.bin/*.tar.gz) - Image should be saved in /cftmp"
    echo  "    no-md5-check - Disable check of the image file for MD5"
    echo  "    factory-default - recovery the configuration to factory default"
}

p2_checking()
{
    # check if partition 2 is available
    status=$(get_fs_status "secondary" "/etc/picos")
    if [[ "${status}" != "up-to-date" ]]; then
        if [[ "${status}" != "ok" ]]; then
            echo "Partition 2 stauts checking failed, upgrade aborted!"
            exit 1
        fi
    fi
    status=$(backup_e2fsck)
    if [[ ${status} -ne 0 ]]; then
        echo "Partition 2 file system checking failed, upgrade aborted!"
        exit 1
    fi

    #check partition size
    partition_size_check
    if [ $? -ne 0 ]; then
        echo "Partition size checking failed, upgrade aborted!"
        exit 1
    fi
}

if [ ! -n "$1" ]; then
    print_help
    exit 1
fi

NAME=""
md5_check=1
factory_default=0
bin_flag=0
bin_param=
while [ "x$1" != "x" ]
do
    case $1 in
      *.tar.gz*)
           NAME=$1
           ;;
       *.bin)
           NAME=$1
           bin_flag=1
           ;;
      "no-md5-check")
           md5_check=0
           ;;
      "factory-default")
           factory_default=1
           bin_param=$1
           ;;
      *)
           echo "invalid option -- '$1'"
           exit 1
           ;;
    esac
    shift 1
done

user_root=`whoami| grep -v grep | grep 'root'|wc -l`

if [[ $user_root -eq 0 ]] ; then
    echo "Only root can upgrade system image, upgrade aborted!"
    echo ""
    exit 1
fi

if [ "$bin_flag" = 1 ]; then
    run_bin $NAME upgrade01 $bin_param
    exit $?
fi

if [ -z "$BACKUP_STORAGE_DEV" ];then
    echo "Missing Recovery Partition. Please create the Recovery Partition"
    exit 0
fi


if [ $factory_default -eq 1 ]; then    
    echo "Restore default fabric configuration"
    if [ -f /ovs/ovs-vswitchd.conf.db ];then
        rm -fr /ovs/ovs-vswitchd.conf.db
    fi
    if [ -f /pica/config/pica_startup.boot ];then
        rm -fr /pica/config/pica_startup.boot
    fi
   
    # for npb
    if [ -f /ovs/portGroup.conf.db ]; then
        rm -fr /ovs/portGroup.conf.db
    fi
    if [ -f /ovs/npb/htdocs/backend/web_api/dns_list.json ]; then
        rm -fr /ovs/npb/htdocs/backend/web_api/dns_list.json
    fi
    if [ -f /ovs/npb/htdocs/backend/web_api/snmp_acl.json ]; then
        rm -fr /ovs/npb/htdocs/backend/web_api/snmp_acl.json
    fi
fi

if [ ! -n "$NAME" ]; then
   if [ $factory_default -eq 1 ]; then
       echo "Rebooting in 10 seconds!"
       sleep 10
       echo "reboot now!"
       reboot -f
   fi 
   exit 0
fi

tar -zxvf $NAME ./etc/lsb-release
if [ "$?" -ne 0 ]; then
    echo "The file (/etc/lsb-release) not found in image!"
    exit 1
fi

current_machine=`cat /etc/lsb-release | grep "DISTRIB_MACHINE" | awk -F = '{print $2}' | tr '[A-Z]' '[a-z]'`
package_machine=`cat ./etc/lsb-release | grep "DISTRIB_MACHINE" | awk -F = '{print $2}' | tr '[A-Z]' '[a-z]'`
if [ -z "$package_machine" ] && [ -z "$current_machine" ]; then
    echo "Fail to check machine type!"
    exit 1
fi
if [ "$current_machine" != "$package_machine" ]; then
    echo "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
    echo "@WARNING: THE IMAGE IS NOT COMPATIBLE TO THE HARDWARE MODEL!@"
    echo "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
    echo "It may damage the system!"
    echo "Press any key to stop"
    SAVEDSTTY=`stty -g`
    stty -echo
    stty cbreak

    for i in 10 9 8 7 6 5 4 3 2 1
    do
        echo -ne "$i "
        if [ "$i" = "1" ];then
            echo "..."
        fi
        read -t 2 -n 1 input

        if [ -n "$input" ];then
            echo ""
            #echo "stop upgrade process"
            stty echo
            stty $SAVEDSTTY
            exit 0
        fi
    done

    stty echo
    stty $SAVEDSTTY
    #echo "WRONG SWITCH model - you are trying to update $MODEL with $NAME file, Please add $MODEL in the image file name."
    #exit 1
fi

MODEL=`version | grep "Hardware Model" | cut -d ':'  -f 2 | sed 's/^[ \t]*//g' | sed 's/[ \t]*$//g'`

echo "Upgrading $MODEL"
if [ ! -f /cftmp/$NAME ]; then
    echo "Image File not found in /cftmp, upgrade aborted!"
    exit 1
fi

if [ -f /pica/config/pica_startup.boot ]; then
    echo "Checking configuration file"
    res=`grep "Has Deprecated Node" /pica/config/pica_startup.boot | grep 1 | wc -l`
    if [ $res -ne 0 ]; then
        echo "Configuration file /pica/config/pica_startup.boot has deprecated node"
        echo "Please remove the deprecated nodes before upgrade, upgrade aborted!"
        exit 1
    fi
fi

cur_version=`cat /etc/lsb-release |grep DISTRIB_RELEASE |awk -F = '{print $NF}' | sed -n "s#\(^[0-9][0-9]*\.[0-9][0-9]*\).*#\1#p"`
new_version=`cat ./etc/lsb-release |grep DISTRIB_RELEASE |awk -F = '{print $NF}'| sed -n "s#\(^[0-9][0-9]*\.[0-9][0-9]*\).*#\1#p"`
if [ -z "$cur_version" ] || [ -z "$new_version" ]; then
    echo "There is something wrong with version check, upgrade aborted!"
    exit 1
fi
if [ `echo "$cur_version $new_version" | tr " " "\n" | sort -V | head -n 1` != "$new_version" ]; then
    if [ -f /etc/picos/switch-public.key -a -f /etc/picos/pica.lic ];then
        expired_date=`license -s |grep "Support End Date" |awk -F \" '{print $4}'`
        if [ ! -n "$expired_date" ]; then
            echo "No expired date information in license data, upgrade aborted!"
            exit 1
        fi
        expired_sec=`date -d $expired_date +%s`
        cd /cftmp
        build_date=`cat ./etc/lsb-release|grep "GA_RELEASE_DATE"|awk -F = '{print $NF}'`
        build_sec=`date -d $build_date +%s`
        rm -fr ./etc
        if [ "$build_sec" -gt "$expired_sec" ];then
            echo "License is expired, a new license is required!"
            exit 0
        fi
    fi    
fi

#do some partition checking
p2_checking

echo "Upgrade $MODEL started" 
if [ $md5_check -eq 1 ]; then
    if [ -f /cftmp/$NAME.md5 ]; then
        echo "Checking MD5 of image"
        cat /cftmp/$NAME.md5 | while read sum file
        do
            prev_sum=$(md5sum /cftmp/$NAME | awk '{print $1}')
            if [ "$sum" != "$prev_sum" ] ||  [ "$file" != "$NAME" ]; then
                echo "MD5 check failed!  MD5 does not match - Deleting file"
                if [ -f /cftmp/$NAME ]; then  
                   `rm -f /cftmp/$NAME`
				fi
                if [ -f /cftmp/$NAME.md5 ]; then  
                   `rm -f /cftmp/$NAME.md5` 
                fi
                if [ -f /cftmp/rootfs.tar.gz ]; then  
                   `rm -f /cftmp/rootfs.tar.gz` 
                fi
                sync
                exit 1
             else
                echo "MD5 Check OK!"
                `rm  -f /cftmp/$NAME.md5`
             fi
        done
    else
        echo "MD5 File not found, upgrade aborted!"
        exit 1
    fi                        
fi 

if [ -f /cftmp/rootfs.tar.gz.md5 ];then
    rm -fr /cftmp/rootfs.tar.gz.md5
fi

if [ -f /cftmp/$NAME ]; then
    `mv  /cftmp/$NAME /cftmp/rootfs.tar.gz`
    sync
    sleep 1
    cd /cftmp
    tar -zxvf rootfs.tar.gz ./etc/p1upgrade.sh
    if [ "$?" -ne 0 ]; then
        echo "The file (/etc/p1upgrade.sh) not found in image!"
        exit 1
    fi

    mv ./etc/p1upgrade.sh /etc/
    rm -fr ./etc
    if [ $factory_default -eq 0 ]; then
        echo "Back up PICOS configuration files"
        IP=`ifconfig eth0|xargs|awk '{print $7}'|sed -e 's/[a-z]*:/''/'`
        DATE=$(date +%Y%m%d)
        #delete space: some name is special, such as "HPE AL 6900"
        MODEL=${MODEL//' '/'_'}
        NEWNAME="CONFIG_FILE_$MODEL-$IP-@$DATE"
        if [ -f /ovs/ovs-vswitchd.conf.db -a -f /pica/config/pica_startup.boot ]; then
            CMD="tar cvzPf /cftmp/$NEWNAME.tgz /ovs/ovs-vswitchd.conf.db /pica/config/pica_startup.boot /etc/picos/picos_start.conf"
        elif [ -f /pica/config/pica_startup.boot ]; then
            CMD="tar cvzPf /cftmp/$NEWNAME.tgz /pica/config/pica_startup.boot /etc/picos/picos_start.conf"
        elif [ -f /ovs/ovs-vswitchd.conf.db ]; then
            CMD="tar cvzPf /cftmp/$NEWNAME.tgz /ovs/ovs-vswitchd.conf.db /etc/picos/picos_start.conf"
        else
            CMD="tar cvzPf /cftmp/$NEWNAME.tgz /etc/picos/picos_start.conf"
        fi
        echo `$CMD`
        echo "Config files saved locally as /cftmp/$NEWNAME.tgz"
    
        if [ -f /etc/picos/switch-public.key -a -f /etc/picos/pica.lic ];then
           echo "Backup PICOS license files"
           NEWNAME="LICENSE_FILE_$MODEL-$IP-@$DATE"
           CMD="tar cvzPf /cftmp/$NEWNAME.tgz /etc/picos/switch-public.key /etc/picos/pica.lic"
           echo `$CMD`
           echo "License files saved locally as /cftmp/$NEWNAME.tgz"
        fi
    fi
    sync
    sleep 1
    echo "Rebooting in 10 seconds!"
    sleep 10 
    echo "reboot now!"
    reboot -f
else 
    echo "Image file not found under /cftmp, upgrade aborted!"				
fi
