#!/bin/bash

# Trap signals during script excute.
if [ -f /OSM/script/os_trap_action.sh ];then
    source /OSM/script/os_trap_action.sh
fi
#包含头脚本
source /OSM/conf/initrd.conf
source /OSM/script/os_load_base.sh
# --------------------------  variables  ------------------------------------- #
#变量定义
#第3次复位上电时进入小系统
G_MAX_RESET_TIMES=3
G_MAX_SYS_RESET_TIME=1440 #minitus
G_SERIOU_RESET=0
G_SERIOUS_COUNT_FILE=/startup_disk/conf/conf_local/serious_count_cfg
RESET_INFO_DB_NAME="/startup_disk/conf/conf_local/reset_record.db"
RESET_INFO_TABLE_NAME="rbtbl"
# --------------------------  functions  ----------------------- ------------- #

SetBootStatus()
{
    G_BOOT_TYPE=`cat /proc/cmdline | egrep -o -m 1 "os_boot_osp|os_only|os_rescue|os_equip_test|os_netboot"`
    if [ "$G_BOOT_TYPE" == "os_equip_test" ]; then
        G_BOOT_TYPE="os_boot_osp"
    fi

    return 0
}

# **************************************************************************** #
# Function Name: OS_SERIOUS_RESET_TIMES
# Description: 获取严重复位的次数，只以当前时间为基准，如果用户修改了硬件时间
#              也已当前时间为基准
# Parameter: none
# Return: 0-succ 1-fail
# **************************************************************************** #
OS_SERIOUS_RESET_TIMES()
{
    local max_reset_sec=$G_MAX_SYS_RESET_TIME
    local cur_time=`date "+%Y-%m-%d %H:%M:%S"`
    local timeBefore=`date "+%Y-%m-%d %H:%M:%S" -d "-${max_reset_sec}min"`
    # 需要判断记录复位的时间小于当前时间，可能存在修改系统时间的场景
    G_SERIOU_RESET=`sqlite3 $RESET_INFO_DB_NAME "select count(*) from ${RESET_INFO_TABLE_NAME} where (resetType like 'watchDog reset' or resetType like 'mce reset' or resetType like 'power lost reset') and datetime(resetTime)>datetime('$timeBefore') and datetime(resetTime)<datetime('$cur_time')"`
    if [ $? != 0 ];then
        OS_echo "upgrade_serious_reset: query data in db failed ($G_SERIOU_RESET)."
        return 1
    fi

    OS_echo "upgrade_serious_reset: G_SERIOU_RESET=$G_SERIOU_RESET in $G_MAX_SYS_RESET_TIME"

    return 0
}

# **************************************************************************** #
# Function Name: OS_RelinkBoot
# Description: relink the boot link
# Parameter: 1-link to dir
# Return:
# **************************************************************************** #
OS_RelinkBoot()
{
    #从L_BOOT_LOCAL 启动
    L_BOOT_LOCAL=$1
    mount -o remount,rw,async $G_DISK_MOUNT_IMAGE
    cd $G_DISK_MOUNT_IMAGE

    rm -rf boot
    ln -s $L_BOOT_LOCAL boot
    cd /
    return 0
}
# **************************************************************************** #
# Function Name: OS_RollBack
# Description: rollback the link
# Parameter: 1-link to dir
# Return:
# **************************************************************************** #
OS_RollBack()
{
    #当前启动类型
    OS_RelinkBoot boot_rescue

    return 0 
}

# **************************************************************************** #
# Function Name: CheckSeriousResetHandle
# Description: 参考os_load_select_ver.sh的严重复位判断如何进入小系统
# Parameter: none
# Return: 0-succ 1-fail
# **************************************************************************** #
function CheckSeriousResetHandle()
{
    if [ ! -f $RESET_INFO_DB_NAME ];then
        OS_echo "upgrade_serious_reset: no record file, exit"
        return 0
    fi
    SetBootStatus
    if [ "$G_BOOT_TYPE" != "os_boot_osp" ]; then
        OS_echo "upgrade_serious_reset: not in os_boot_osp, Need not Rollback, exit"
        return 0
    fi
    if [ -f $G_SERIOUS_COUNT_FILE ];then
        local tmp1=`cat $G_SERIOUS_COUNT_FILE`
        OS_echo "upgrade_serious_reset: reset count is $tmp1"   
        local tmp=`echo $tmp1| grep -E "0|1|2|3|4"`
        if [ -n "$tmp" ];then
            let G_MAX_RESET_TIMES=$tmp+1  
        fi
    fi
    #step 3:如果正常启动，判断30分钟验证复位次数
    L_TMP=`ls -l $G_DISK_MOUNT_IMAGE | grep -a "boot ->" |awk '{print $11}'`
    if [ "$L_TMP" = "boot_osp" -o "$L_TMP" = "boot_osp_bak" ] ; then
        OS_SERIOUS_RESET_TIMES    
        if [ $? -eq 1 ] ; then
            OS_echo "upgrade_serious_reset: cant not get OS_SERIOUS_RESET_TIMES."
            return 0
        fi

        #默认24小时大于或者等于3次就回退
        if [ "$G_SERIOU_RESET" -ge "$G_MAX_RESET_TIMES" ]; then
            L_FAIL_VER=`cat $G_DISK_MOUNT_IMAGE/boot/versions.conf |grep "Version" |head -1 |tail -1`
            if [ -z "${L_FAIL_VER}" ];then
                L_FAIL_VER="current version"
                OS_echo "upgrade_serious_reset: get version fail, set version=${L_FAIL_VER}"
            fi
            OS_echo "upgrade_serious_reset: Ver ${L_FAIL_VER} load fail because serious reset over $G_MAX_RESET_TIMES in $G_MAX_SYS_RESET_TIME."
            #回退到rescue
            OS_RollBack
            return 0
        fi
    fi
}
function PATCH_START()
{
    #上电恢复补丁时才生效
    local pid_server=$(ps -ww -eo pid,cmd | grep "/OSM/bin/omm_upd_server.bin" | grep -v grep | awk '{print $1}')
    local pid_agent=$(ps -ww -eo pid,cmd | grep "/OSM/bin/omm_upd_agent.bin" | grep -v grep | awk '{print $1}')
    if [ "$pid_server" = "" ] && [ "$pid_agent" = "" ]; then
        OS_echo "upgrade_serious_reset: It is poweron resume."
        CheckSeriousResetHandle
        return 
    fi
    OS_echo "upgrade_serious_reset: It is installing, do nothing."
    return 
}
function PATCH_END()
{
    return
}
function PATCH_ROLLSTART()
{
    return
}
function PATCH_ROLLEND()
{
    
    return
}
#start：打补丁前需要执行的操作，脚本的执行时间点在替换文件前
#end：打补丁后需要执行的操作，脚本的执行时间点在替换文件后
#rollstart：回滚补丁时需要执行的操作，脚本的执行时间点在文件被恢复之前。
#rollend：回滚补丁时需要执行的操作，脚本的执行时间点在文件被恢复之后。

L_CMD=$1
OS_echo "command is $L_CMD"
case $L_CMD in
        "start") 
                PATCH_START
                ;;
        "end") 
                PATCH_END
                ;;
        "rollstart") 
                PATCH_ROLLSTART
                ;;
        "rollend") 
                PATCH_ROLLEND
                ;;
        *)
                OS_echo  "unsupported option."
esac
exit 0

