#!/bin/sh
option=""
file=""
PASS=1
FAIL=0
#exit value--used by rtest 
OK=0
ERROR=-1
TEMPDEB=/upload/temp.deb
UPDATEINFO=/tmp/.updateinfo
BACKGROUND_INSTALL_FLAG="/tmp/.background_install"
UNINSTALL_DEB_NAME=/tmp/.uninstall_deb_name
UNINSTALLINFO=/tmp/.uninstallinfo
DPKG_DIR=/app/dpkg
APPLIST=${DPKG_DIR}/app_list
APPSTATUS=${DPKG_DIR}/status
SYSAPPLIST=${DPKG_DIR}/sys_app_list
MERGEAPPLIST=${DPKG_DIR}/merge_app_list
KERNELLIST=${DPKG_DIR}/kernel_list
#cat app_list sys_app_list |sort|uniq
ROUTER_DIR=/boot/router
RBTGPGCLI=/usr/scripts/rbt_gpg_usr.sh
SWAPFILES=/overlay/upper/.swapfiles
#SWAPFILES=/data/.swapfiles
verify_result=${FAIL}
DEBTYPE=""
DEPENDS=""
verify_flag=`renv get verify_flag 2>/dev/null` 
handle_usb_upgrade=`renv get handle_usb_upgrade 2>/dev/null` 
dev_mode_file="/overlay/.rbt-system-mgmt-developer-mode"
if [ -f "${dev_mode_file}" ]; then
    dev_mode_flag="$(cat "${dev_mode_file}" 2>/dev/null | tr -d ' \t\r\n')"
    if [ "${dev_mode_flag}" = "1" ]; then
        verify_flag="skip"
        logger -p user.debug "[sysupgrade]:developer mode enabled, skip signature verification"
    fi
fi
#remove org lock
org_lock_flag="/tmp/.sysupgrade_lock"
if [ -f ${org_lock_flag} ];then
    rm ${org_lock_flag} -rf
fi

#use new lock
lock_flag="/tmp/.sysupgrade_lock_exec"
exec 200>${lock_flag}
flock -x 200


swapon_safe_remove()
{
    local swapfiles=$1
    if [ -e  ${swapfiles} ];then
        logger -p user.debug "[sysupgrade]:free swap space."
        swapoff ${swapfiles}
        rm -rf ${swapfiles}
    fi
}

swapon_create()
{
    local swapfiles=$1
    local file_size=$2
    local flash_available_size=$(df -m /overlay/upper |awk 'NR==2'|awk '{print $4}')
    local max_swap_size=$((flash_available_size / 2))
    local swap_size=$(($file_size * 2))

    if [ "$swap_size" -gt $max_swap_size ]; then
        swap_size=$max_swap_size
    fi

    logger -p user.debug "[sysupgrade]:create swap space, size: ${swap_size}MB"

    swapon_safe_remove ${swapfiles}
    fallocate -l ${swap_size}m ${swapfiles}
    chmod 600 ${swapfiles}
    mkswap ${swapfiles}
    swapon ${swapfiles}
}

swapon_create_if_needed()
{
    local file_path=$1
    local swapfiles=$2
    local file_size=$(du -m "$file_path" | cut -f1)
    local available_ram=$(free -m |awk 'NR==2'|awk '{print $7}')
    if [ "$file_size" -gt $((available_ram / 2)) ]; then
            logger -p user.debug "[sysupgrade]:file size ($file_size MB) is larger than half of available RAM ($available_ram MB), create swap space."
            swapon_create ${swapfiles} ${file_size}
    else
            logger -p user.debug "[sysupgrade]:no need to create swap space."
    fi
}

: <<'COMMENT'   #deprecated
get_app_list()
{
    local apps=$(software_update get-installed-rosp-apps)
    local base_system=$(dpkg -l | grep base-system | awk '{print $2}' | head -n 1)
    local deps_raw=$(dpkg -s $base_system | grep "^Depends:")
    local deps_list=$(echo "$deps_raw" | sed -e 's/Depends: //' \
                                  -e 's/ ([^)]*)//g' \
                                  -e 's/, */\n/g' \
                                  -e 's/^[[:space:]]*//;s/[[:space:]]*$//')

    echo "$apps" | while IFS= read -r app; do
        if [ -z "$app" ]; then
            continue
        fi

        if echo "$deps_list" | grep -q -x -- "$app"; then
            continue
        fi
        echo "$app"
    done
}
COMMENT

get_sys_app_list()
{
    local apps=$(software_update get-installed-rosp-apps)
    local base_system=$(dpkg -l | grep base-system | awk '{print $2}' | head -n 1)
    local deps_raw=$(dpkg -s $base_system | grep "^Depends:")

    local deps_list=$(echo "$deps_raw" | sed -e 's/Depends: //' \
                                  -e 's/ ([^)]*)//g' \
                                  -e 's/, */\n/g' \
                                  -e 's/^[[:space:]]*//;s/[[:space:]]*$//')

    echo "$apps" | while IFS= read -r app; do
        if [ -z "$app" ]; then
            continue
        fi

        if echo "$deps_list" | grep -q -x -- "$app"; then
            echo "$app"
        fi
    done
    echo "rosp-core"
}

init_sys_kernel_list()
{
    rm ${SYSAPPLIST} -rf
    rm ${KERNELLIST} -rf
    local sys_apps=$(get_sys_app_list)
    echo "$sys_apps" >> ${SYSAPPLIST}

    local kernel=`dpkg -l | grep linux-image | grep -v linux-image-rt | awk '{print $2}'`
cat >> ${KERNELLIST} <<EOL
${kernel}
EOL
}

: <<'COMMENT'   #deprecated
init_app_list()
{
    rm ${APPLIST} -rf
    local apps=$(get_app_list)
    echo "$apps" >> ${APPLIST}
}
COMMENT

init_rsa_time()
{
    local rsa_year=2022
    local rsa_time=2022-01-01
    local year=`date "+%Y"`
    if [ $year -lt $rsa_year ];then
        logger -p user.debug "[sysupgrade]:init rsa time."
        date -s "$rsa_time" >/dev/null
    fi
}

get_reboot_needed()
{
    package_name=$1
    firmware_reboot_list="system- extend- linux-u-boot linux-image"
    reboot_needed=0
    for file  in $firmware_reboot_list;do
        reboot_needed=`echo $package_name |grep $file |wc -l`
        if [ "$reboot_needed" != "0" ];then
            reboot_needed=1
            break
        fi
    done
    if [ "$reboot_needed" = "0" ];then
        if [ "$package_name" = "rosp" ];then
            reboot_needed=1
        fi
    fi
    echo "$reboot_needed"
}

# Wait for background install to complete (used by packages like rosp that spawn background install.sh)
# Returns: 0 = success or no background install, 1 = failed (process disappeared without result)
# Note: Will wait indefinitely as long as install.sh process is running
wait_background_install() {
    local count=0
    local grace_wait=5
    
    # If flag file doesn't exist, no background install is running
    if [ ! -f "${BACKGROUND_INSTALL_FLAG}" ]; then
        return 0
    fi
    
    logger -p user.debug "[sysupgrade]: background install detected, waiting for completion..."
    echo "[sysupgrade]: background install detected, waiting for completion..." >/dev/console
    
    while true; do
        # Check if result has been written
        if grep -q "^result=" "${BACKGROUND_INSTALL_FLAG}" 2>/dev/null; then
            local result=$(grep "^result=" "${BACKGROUND_INSTALL_FLAG}" | tail -1 | cut -d= -f2 | cut -d' ' -f1)
            logger -p user.debug "[sysupgrade]: background install completed with result: ${result}"
            echo "[sysupgrade]: background install completed with result: ${result}" >/dev/console
            
            # Clean up flag file
            rm -f "${BACKGROUND_INSTALL_FLAG}"
            
            if [ "${result}" = "success" ]; then
                return 0
            else
                return 1
            fi
        fi
        
        # Check if install.sh process is still running
        if ! pgrep -f "install.sh" > /dev/null 2>&1; then
            # Race fix: install.sh may have just exited after writing result.
            # Give a short grace window to re-check the flag file before declaring failure.
            local w=0
            logger -p user.debug "[sysupgrade]: install.sh not running, waiting ${grace_wait}s for result flush..."
            while [ "${w}" -lt "${grace_wait}" ]; do
                if grep -q "^result=" "${BACKGROUND_INSTALL_FLAG}" 2>/dev/null; then
                    local result=$(grep "^result=" "${BACKGROUND_INSTALL_FLAG}" | tail -1 | cut -d= -f2 | cut -d' ' -f1)
                    logger -p user.debug "[sysupgrade]: background install completed with result: ${result}"
                    echo "[sysupgrade]: background install completed with result: ${result}" >/dev/console

                    # Clean up flag file
                    rm -f "${BACKGROUND_INSTALL_FLAG}"

                    if [ "${result}" = "success" ]; then
                        return 0
                    else
                        return 1
                    fi
                fi
                sleep 1
                w=$((w + 1))
            done

            # Process is gone and still no result written, consider as failure
            logger -p user.debug "[sysupgrade]: background install process disappeared without result"
            echo "[sysupgrade]: background install process disappeared without result" >/dev/console
            rm -f "${BACKGROUND_INSTALL_FLAG}"
            return 1
        fi
        
        sleep 1
        count=$((count + 1))
        
        # Log progress every 60 seconds
        if [ $((count % 60)) -eq 0 ]; then
            logger -p user.debug "[sysupgrade]: still waiting for background install... (${count}s elapsed)"
        fi
    done
}

: <<'COMMENT'   #deprecated
update_app_status()
{
    #cat ${SYSAPPLIST} ${APPLIST} 2>/dev/null | sort | uniq  > ${MERGEAPPLIST}
	apps=$(software_update get-installed-rosp-apps)
	apps="$apps rosp-core"
    rm ${APPSTATUS} -rf
    logger -p user.debug "[sysupgrade]:update_app_status"
	for line in $apps; do
if [ "${line}" != "" ];then
        deb_info=`dpkg -l ${line} 2>/dev/null | grep "^ii"`
        if [ "${deb_info}" = "" ];then
            deb_info=`dpkg -l ${line} 2>/dev/null | grep "^iF"`
        fi
if [ "${deb_info}" != "" ];then
        name=`echo $deb_info | awk '{print $2}'`
        version=`echo $deb_info | awk '{print $3}'`
        desc=`echo $deb_info | awk  '{for (i=5;i<=NF;i++)printf("%s ", $i);print ""}'`
cat >> ${APPSTATUS} <<EOL
Package: ${name} 
Description: ${desc} 
Version: ${version}
EOL
fi
fi
    done
}
COMMENT

update_app_status()
{
    cat ${SYSAPPLIST} ${APPLIST} 2>/dev/null | sort | uniq  > ${MERGEAPPLIST}
    rm ${APPSTATUS} -rf
    logger -p user.debug "[sysupgrade]:update_app_status"
    while read line
    do
if [ "${line}" != "" ];then
        deb_info=`dpkg -l ${line} 2>/dev/null | grep "^ii"`
        if [ "${deb_info}" = "" ];then
            deb_info=`dpkg -l ${line} 2>/dev/null | grep "^iF"`
        fi
if [ "${deb_info}" != "" ];then
        name=`echo $deb_info | awk '{print $2}'`
        version=`echo $deb_info | awk '{print $3}'`
        desc=`echo $deb_info | awk  '{for (i=5;i<=NF;i++)printf("%s ", $i);print ""}'`
cat >> ${APPSTATUS} <<EOL
Package: ${name} 
Description: ${desc} 
Version: ${version}
EOL
fi  
fi
    done <${MERGEAPPLIST}
}

update_sysapp_kernel_list()
{
    logger -p user.debug "[sysupgrade]:start to update sysapp list and kernel list"
    local debname=$1
    local is_kernel=`echo ${debname} |grep "^linux-image-" |wc -l`
    if [ "${is_kernel}" = "1" ];then
        rm ${ROUTER_DIR}/linux-image-* -rf
        sed -i  "/^linux-image-.*/d" ${APPLIST} 2>/dev/null
        sed -i  "/^linux-image-.*/d" ${SYSAPPLIST} 2>/dev/null
        sed -i  "/^linux-image-.*/d" ${KERNELLIST} 2>/dev/null
        echo ${debname} >> ${APPLIST}
        echo ${debname} >> ${SYSAPPLIST}
        echo ${debname} >> ${KERNELLIST}
        logger -p user.debug "[sysupgrade]:update sysapp list and kernel list done.kernel name [${debname}]"
    else
        logger -p user.debug "[sysupgrade]:not kernel,no need to update."
    fi
}

if [ "${1}" = "remove" ] ;then
    if [ "$2" != "" ];then
	apt -y purge ${2} > ${UNINSTALLINFO}
        cat ${UNINSTALLINFO} |grep "^Removing" | cut -d " " -f 2 > ${UNINSTALL_DEB_NAME}
       	while IFS= read -r un_deb_name; do
            if [ "$un_deb_name" != "" ];then
                logger -p user.debug "[sysupgrade]: removing ${un_deb_name}"
                echo "[sysupgrade]: removing ${un_deb_name}" >/dev/console
                sed -i  "/^${un_deb_name}$/d" ${APPLIST} 2>/dev/null
                logger -p user.debug "[sysupgrade]: removing backup deb files [${ROUTER_DIR}/${un_deb_name}.deb]"
                rm -rf ${ROUTER_DIR}/${un_deb_name}.deb
                update_app_status
            else
                logger -p user.debug "[sysupgrade]: removing fail"
                echo "[sysupgrade]: removing fail" >/dev/console
            fi
	done < ${UNINSTALL_DEB_NAME}
    else
        logger -p user.debug "[sysupgrade]: unistall fail, file =null"
        echo "[sysupgrade]: unistall fail, file =null" >/dev/console
    fi
    exit $OK
elif [ "${1}" = "init_sysypgrade_status" ] ;then
    init_sys_kernel_list
    #init_app_list
    update_app_status
    swapon_safe_remove ${SWAPFILES}
    rm -f $TEMPDEB
    exit $OK
elif [ "${1}" = "update_sysapp_kernel_list" ] ;then
    if [ "$2" != "" ];then
        update_sysapp_kernel_list $2
    fi
    exit $OK
fi

if [ $# -eq 0 ]; then
    logger -p user.debug "[sysupgrade]:upgrade fail, no parameters provided"
    exit $ERROR
fi

#temporarily skip -q,-k options,as rtest do not specify any options
if [ "${1}" = "-q" ] || [ "${1}" = "-k" ];then
    option=$1
    file=$2
else
    file=$1
fi

if [ "${file}" = "" ];then
        logger -p user.debug "[sysupgrade]:upgrade fail ,file=[null]"
        exit $ERROR
fi

if [ ! -d ${DPKG_DIR} ]; then 
    mkdir ${DPKG_DIR}
fi

if [ ! -d ${ROUTER_DIR} ]; then 
    mkdir ${ROUTER_DIR}
fi

set_fail_status()
{
    renv set sysupgrade_status fail
    renv set sysupgrade_fail_reason "$1"
    renv set sysupgrade_progress 10
    renv set sysupgrade_total 0
}

set_success_status()
{
    renv set sysupgrade_status success
    if [ "$1" = "kernel" ];then
        renv set sysupgrade_type kernel
    else
        renv set sysupgrade_type firmware
    fi
    renv set sysupgrade_progress 100
    renv set sysupgrade_total 0
}

init_renv_status()
{
    renv del sysupgrade_status 2>/dev/null
    renv del sysupgrade_fail_reason 2>/dev/null
    renv del sysupgrade_progress 2>/dev/null
    renv del sysupgrade_total 2>/dev/null
    renv del sysupgrade_type 2>/dev/null
}

deb_info_remove()
{
    local deb_name_remove=$1
    local oem_exist="0"
    if [ -f ${APPLIST} ];then
        oem_exist=`cat ${APPLIST} |grep "^${deb_name_remove}" |wc -l`
        if [ "${oem_exist}" != "0" ];then
            logger -p user.debug "[sysupgrade]:remve ${deb_name_remove} info"
            sed -i  "/^${deb_name_remove}/d" ${APPLIST} 2>/dev/null
        fi
    fi
    if [ -f ${ROUTER_DIR}/${deb_name_remove}.deb ];then
        logger -p user.debug "[sysupgrade]:remve ${deb_name_remove} deb"
        rm -rf ${ROUTER_DIR}/${deb_name_remove}.deb 
    fi
}

oem_remove()
{
    deb_info_remove rosp-oem
    deb_info_remove rosp-roem
}

overlayfs_remove()
{
    deb_info_remove $1
}

update_app_list_and_backup_deb()
{
    logger -p user.debug "[sysupgrade]:update_app_list_and_backup_deb"
    local deb_name=`cat ${UPDATEINFO} |grep "^Setting up" | cut -d " " -f 3`
    local deb_exist="0"
    local deb_file=$1
    if [ -f ${APPLIST} ];then
        while read line
        do
            if [ "$deb_name" = "$line" ];then
                deb_exist="1"
                break
            fi  
        done <${APPLIST}
    fi
    if [ "$deb_exist" = "0" ] && [ "${deb_name}" != "" ];then
        logger -p user.debug "[sysupgrade]:update deb_name info [${deb_name}]"
        echo ${deb_name} >> ${APPLIST}
    else
        logger -p user.debug "[sysupgrade]:deb_name already exists ,no need to update"
    fi
    if [ "${deb_name}" != "" ];then
        update_sysapp_kernel_list ${deb_name}
        #backup_deb
        logger -p user.debug "[sysupgrade]:backup deb packages [${ROUTER_DIR}/${deb_name}.deb]"
        while read kernel_line
        do
            if [ "$deb_name" = "${kernel_line}" ];then
                DEBTYPE="kernel"
                logger -p user.debug "[sysupgrade]:match kernel list"
                break
            fi  
        done <${KERNELLIST}

        #The requirement info of reboot should be showed when upgrading uboot/system/extend partition or kernel image.
        needed_reboot=`get_reboot_needed $deb_name`
        if [ "$needed_reboot" = "1" ] ;then
            DEBTYPE="kernel"
        fi

        #For MES upgrade .skip backup deb
        if [ "${DEBTYPE}" != "kernel" ] && [ "${verify_flag}" != "skip" ];then 
            logger -p user.debug "[sysupgrade]:backup ok."
            cp ${deb_file} ${ROUTER_DIR}/${deb_name}.deb -rf
        else
            logger -p user.debug "[sysupgrade]:bakcup skip."
        fi

        if [ "$needed_reboot" = "1" ] ;then
            overlayfs_remove $deb_name
        fi
    fi

    oem_remove
}

try_second_upgrade()
{
    logger -p user.debug "[sysupgrade]:check second upgrade"
    local deb_name=`cat ${UPDATEINFO} |grep "^Setting up" | cut -d " " -f 3`
    local deb_file=$1
    if [ "$deb_name" = "" ];then
        logger -p user.debug "[sysupgrade]:check depends"
        local depends=`dpkg -I ${deb_file} |grep "Depends:"|cut -d ":" -f 2 |sed  "s/,/ /g" |sed "s/([^)]*)//g"`
        if [ "$depends" != "" ];then
            logger -p user.debug "[sysupgrade]:depends [$depends], now start second upgrade"
            DEPENDS=`dpkg -I ${deb_file} |grep "Depends:"|cut -d ":" -f 2`
            dpkg --configure -a
            apt update
            apt -y  --fix-broken install  `readlink -f  $deb_file`
            dpkg -i --force-confask --force-confnew  ${deb_file} > ${UPDATEINFO}
        else
            logger -p user.debug "[sysupgrade]:no depends, not need second upgrade"
        fi
    else
        logger -p user.debug "[sysupgrade]:dpkg upgrade success, not need second upgrade"
    fi
}

set_upgrade_status()
{
    local deb_name=`cat ${UPDATEINFO} |grep "^Setting up" | cut -d " " -f 3`
    if [ "$deb_name" = "" ];then
        if [ "$DEPENDS" = "" ];then
            set_fail_status "Upgrade failed"
        else
            set_fail_status "Upgrade failed, depends $DEPENDS"
        fi
    else
        set_success_status ${DEBTYPE}
    fi
}

check_file_type()
{
    local file_path=$1
    local header=$(dd if="$file_path" bs=4 count=1 2>/dev/null | xxd -p)

    if [ "$header" = "213c6172" ]; then
        return 1
    elif [ "$header" = "1f8b0800" ]; then
        return 2
    fi

    return 0
}

verify_ruf_app()
{
    local file_path=$1
    local verify_result=$FAIL
    local gpg_output

    gpg_output=$(gpg --verify ${file_path} 2>&1)
    if echo "$gpg_output" | grep -q "Good signature"; then
        verify_result=$PASS
        logger -p user.debug "[sysupgrade]:RUF file GPG verification passed"
    else
        verify_result=$FAIL
        logger -p user.debug "[sysupgrade]:RUF file GPG verification failed"
    fi

    return ${verify_result}
}

try_install_ruf_app()
{
    local file_path=$1
    local tmp_file_path=${file_path}.tmp

    rm -rf ${tmp_file_path}
    gpg --output ${tmp_file_path} --decrypt ${file_path} > /dev/null 2>&1
    mv ${tmp_file_path} ${file_path}

    header=$(dd if="$file_path" bs=4 count=1 2>/dev/null | xxd -p)
    if [ "$header" != "b7efedd1" ]; then
        logger -p user.debug "[sysupgrade]:RUF file header verification failed"
        return $FAIL
    fi

    logger -p user.debug "[sysupgrade]:try to install ruf app"

    software_update restore ${file_path} > /dev/null 2>&1
    if [ $? != 0 ]; then
        logger -p user.debug "[sysupgrade]:RUF file restore failed"
        return $FAIL
    fi

    cd /upload
    ar -x ${file_path}
    if [ ! -f data.tar.xz ]; then
        logger -p user.debug "[sysupgrade]:RUF file data not found"
        return $FAIL
    fi

    mkdir -p /upload/data
    tar -xvf data.tar.xz -C /upload/data > /dev/null 2>&1
    if [ ! -f /upload/data/control ]; then
        logger -p user.debug "[sysupgrade]:RUF file control not found"
        return $FAIL
    fi

    if [ ! -f /upload/data/install ]; then
        logger -p user.debug "[sysupgrade]:RUF file install not found"
        return $FAIL
    fi

    chmod +x /upload/data/install
    /upload/data/install > ${UPDATEINFO} 2>&1
    if [ $? != 0 ]; then
        logger -p user.debug "[sysupgrade]:RUF file install failed"
        return $FAIL
    fi

    rm -rf /upload/data
    rm -rf /upload/data.tar.xz

    software_update update-app-status

    logger -p user.debug "[sysupgrade]:RUF file install success"

    return $PASS
}

init_rsa_time
init_renv_status
logger -p user.debug "[sysupgrade]:try to upgrade file=[${file}] ,skip option=[${option}]"
#echo "[sysupgrade]:try to upgrade file=[${file}] ,skip option=[${option}]" >/dev/console

rm ${TEMPDEB} -rf
mkdir -p /upload/

check_file_type ${file}
file_type=$?
logger -p user.debug "[sysupgrade]:file_type=[${file_type}]"

if [ ${file_type} = 2 ]; then
    rbt-system-mgmt clone restore ${file} -y > /dev/null 2>&1
    if [ $? = 0 ]; then
        logger -p user.debug "[sysupgrade]:clone package install success"
        exit $OK
    else
        logger -p user.debug "[sysupgrade]:clone package install failed"
        exit $ERROR
    fi
fi

##temporarily use pass -ubioySHyt24N
#${RBTGPGCLI} action=gpg_package_decrypt  pass=ubioySHyt24N deb_file=${file}  out=${TEMPDEB}
#decrypt_result="$?"
swapon_safe_remove ${SWAPFILES}
if [ "${verify_flag}" = "skip" ]; then
    logger -p user.debug "[sysupgrade]:skip sysupgrade verify"
    result=$PASS
    TEMPDEB=${file}
else
    if [ "${handle_usb_upgrade}" = "true" ]; then
        cp ${file} ${TEMPDEB}
    else
        mv ${file} ${TEMPDEB}
    fi
    decrypt_result=$PASS
    if [ ${decrypt_result} = "$PASS" ]; then
        swapon_create_if_needed  ${TEMPDEB} ${SWAPFILES}

        if [ ${file_type} = 1 ]; then
            ${RBTGPGCLI} action=verify deb_file=${TEMPDEB}
            verify_result=$?
        else
            verify_ruf_app ${TEMPDEB}
            verify_result=$?
        fi
        swapon_safe_remove ${SWAPFILES}
    fi
    result="${verify_result}"
fi

if [ ${result} = "$PASS" ]; then
    logger -p user.debug "[sysupgrade]:gpg verify pass ,start to upgrade [${file}]"
    echo "[sysupgrade]:gpg verify pass ,start to upgrade [${file}]" >/dev/console

    if [ ${file_type} = 1 ]; then
        #for modem firmware
        dname=`dpkg -I ${TEMPDEB} | grep Package | awk '{print $2}'`
        if [ "${dname}" = "modem-firmware" ] || [ "${dname}" = "quectel-firmware" ]; then
            sh /usr/scripts/kill_modemd
            index=0
            while [ $((index++)) -lt 20 ]
            do
                if [ -z "$(pgrep modemd)" ]; then
                    break;
                fi
                sleep 1
            done
            dpkg -i --force-confask --force-confnew  ${TEMPDEB}
            if [ "${dname}" = "quectel-firmware" ]; then
                args=`cat /tmp/quectel-update-args`
	    else
                args=`cat /tmp/modem-update-args`
            fi
            modem_update ${args}
            result=$?
            dpkg -P ${dname}
            if [ ${result} == 0 ]; then
                logger -p user.debug "[sysupgrade]:upgrade [${file}] done"
                echo "[sysupgrade]:upgrade [${file}] done" >/dev/console
            else
                logger -p user.debug "[sysupgrade]:upgrade [${file}] fail"
                echo "[sysupgrade]:upgrade [${file}] fail" >/dev/console
            fi
            if ! [ "${verify_flag}" = "skip" ]; then
                if [ "${handle_usb_upgrade}" != "true" ]; then
                    rm -f $TEMPDEB ${file}
                fi
            fi
            renv del modem_debug
            service_ros modem restart &
            flock -u 200
            exit ${result}
        fi
        #for modem firmware

        dpkg -i --force-confask --force-confnew  ${TEMPDEB} > ${UPDATEINFO}

        sqfs_path="/opt/upgrade/system/system.squashfs"
        if [[ "$dname" =~ "system-" ]] && [ -r "${sqfs_path}" ]; then
            source /lib/rbt-system-mgmt/general
            if type  sqfs_sign_check > /dev/null 2>&1;then
                echo "checking sqfs signature ..." > /dev/console
                if ! sqfs_sign_check "${sqfs_path}" true; then
                    errmsg=$(cat << 'EOF'
[SECURITY] Signature Verification failed! Origin of the package cannot be trusted. Upgrade aborted to protect system security.
EOF
                    )
                    rm -f /opt/upgrade/system/*.squashfs /opt/upgrade/extend/*.squashfs
                    # also eliminate kernel
                    if [ -r /data/boot/kernel.img ]; then
                         mv /data/boot/kernel.img /data/boot/kernel.img.old
                    fi
                    logger -p user.error "${errmsg}"
                    set_fail_status "${errmsg}"
                    exit $ERROR
                fi
            else 
                echo "The sqfs_sign_check() is not found, sqfs signature check aborted!" > /dev/console
            fi
        fi

        #for MES verify
        if [ "${verify_flag}" = "skip" ]; then
            dname=`cat ${UPDATEINFO} |grep "^Setting up" | cut -d " " -f 3`
            if [ "${dname}" = "" ];then
                logger -p user.debug "[sysupgrade]:skip verify and upgrade error"
                set_upgrade_status
                exit $ERROR
            fi
        fi
        #for MES verify end
        
        # Wait for background install if any (e.g., rosp package)
        # Must be before try_second_upgrade to ensure /tmp/.updateinfo has final state
        if ! wait_background_install; then
            set_fail_status "background install failed"
            logger -p user.debug "[sysupgrade]: upgrade [${file}] failed due to background install failure"
            echo "[sysupgrade]: upgrade [${file}] failed due to background install failure" >/dev/console
            if ! [ "${verify_flag}" = "skip" ]; then
                if [ "${handle_usb_upgrade}" != "true" ]; then
                    rm -f $TEMPDEB ${file}
                fi
            fi
            exit $ERROR
        fi
        
        try_second_upgrade ${TEMPDEB}
        update_app_list_and_backup_deb ${TEMPDEB} 
        update_app_status
        sync
        set_upgrade_status
        logger -p user.debug "[sysupgrade]:upgrade [${file}] done"
        echo "[sysupgrade]:upgrade [${file}] done" >/dev/console
        if ! [ "${verify_flag}" = "skip" ]; then
            if [ "${handle_usb_upgrade}" != "true" ]; then
                rm -f $TEMPDEB ${file}
            fi
        fi
        exit $OK
    else
        try_install_ruf_app ${TEMPDEB}
        dpkg --configure -a
        sync
        set_upgrade_status
        logger -p user.debug "[sysupgrade]:upgrade [${file}] done"
        echo "[sysupgrade]:RUF file install success" >/dev/console
        if ! [ "${verify_flag}" = "skip" ]; then
            if [ "${handle_usb_upgrade}" != "true" ]; then
                rm -f $TEMPDEB ${file}
            fi
        fi
        exit $OK
    fi
else
    set_fail_status "Signature Verification Failed! Origin of the package cannot be trusted. Upgrade aborted to protect system security."
    logger -p user.debug "[sysupgrade]:gpg verify fail,do not upgrade"
    echo "[sysupgrade]:gpg verify fail,do not upgrade" >/dev/console
    if ! [ "${verify_flag}" = "skip" ]; then
        rm -f $TEMPDEB ${file}
    fi
    exit $ERROR
fi
