#!/bin/bash
# preinst - upgrade pre-install script
##
DPKG=${DPKG_MAINTSCRIPT_PACKAGE}
DSCRIPT=${DPKG_MAINTSCRIPT_NAME}
dpkgParam=( `echo ${@}` )
action=${dpkgParam[0]:-"none"}
# extract package name and container names
pkg_name=${DPKG}
pkg_id=${pkg_name%%-*}
pkg_gtype=${pkg_name#*-}
pkg_gtype=${pkg_gtype%%-*}; [ "$pkg_gtype" == "$pkg_id" ] && pkg_gtype=""
pkg_ctype=${pkg_name##*-};  [ "$pkg_ctype" == "$pkg_id" ] && pkg_ctype=""
isImage="true"
[ -n "$pkg_gtype" ] && [ -n "$pkg_ctype" ] && isImage="false"
echo "isImage=${isImage}"
echo "Master package name: ${pkg_id}"
[ -n "${pkg_gtype}" ] && echo "Group-container    : ${pkg_gtype}"
[ -n "${pkg_ctype}" ] && echo "Component-container: ${pkg_ctype}"
echo "${DPKG}-${DSCRIPT}: action=${action}"
[ "${action}" == "install" ] && [ -f /tmp/fresh_install ] && echo "${DPKG}-${DSCRIPT}: host-install in progress, skipping" && exit 0
    
source /usr/local/sbin/data-volume-config_helper.sh 2>/dev/null
[ -f /usr/local/sbin/drive_helper.sh ] && source /usr/local/sbin/drive_helper.sh 2>/dev/null
source /etc/system.conf 2>/dev/null

## get common include from tmp debian extraction directory
source /var/lib/dpkg/tmp.ci/deb_include

currentRootDevice=`cat /proc/cmdline | awk -F= 'BEGIN{RS=" "}{ if ($1=="root") print $2 }'`
echo "currentRootDevice=${currentRootDevice}"
upgradeDevice=""
upgradePath="/"
#-----------------------------------------------------------------
# The following parameter initializations use pre-existing scripts
#-----------------------------------------------------------------
disk="/dev/sda"
rootfsDisk1="${disk}1"
rootfsDisk2="${disk}2"
driveList=(`internalDrives`)
DVC_DRIVE_COUNT=${#driveList[@]}
[ "${DVC_DRIVE_COUNT}" == "1"  ] && upgradePart="${rootfsDisk1}"
[ "${DVC_DRIVE_COUNT}" == "2"  ] && upgradePart="`SATADevice 1`1"

## Section: Functions

breakRaid ()
{
   # Break raid, create new raid mdadm upgrade device, and re-format the file system
   echo "Prepare for upgrade pkg install..."
   sync
   mdadm --wait ${currentRootDevice}
   mdadm ${currentRootDevice} -f ${upgradePart}
   mdadm --wait ${currentRootDevice}
   mdadm ${currentRootDevice} -r ${upgradePart}
   mdadm --wait ${currentRootDevice}
   sleep 1
   # clear out any old md superblock data
   mdadm --zero-superblock --force --verbose ${upgradePart}
    sync
    sleep 1
   [ "${DVC_DRIVE_COUNT}" == "1" ] && mdadm --create ${upgradeDevice} --verbose --metadata=0.90 --raid-devices=2 --level=raid1 --run ${upgradePart} missing 2>/dev/null
   [ "${DVC_DRIVE_COUNT}" == "2" ] && mdadm --create ${upgradeDevice} --verbose --metadata=0.90 --raid-devices=4 --level=raid1 --run ${upgradePart} missing missing missing 2>/dev/null
   mdadm --wait ${upgradeDevice}
   sleep 1
   sync
}

start_timeout()
{
# subshell, catchall error, if we never progress for 10 minutes.
(
    count="0"
    while true; do
        sleep 10
        current_update_status=`cat /tmp/fw_update_status`
        if [ "${current_update_status}" != "upgrading 10" ]; then
            break;
        elif [ $count -ge 60 ]; then 
            echo "Unpack timeout occurred"
            error="failed 202 \"upgrade download failure\""
            echo  ${error} > /tmp/fw_update_status
            echo ${error}
            update_log "preinst: ERROR unpack timeout"
            send_update_log
            restoreRaid
            break;
        fi
        count=$[$count+1]
    done
) &
}

## Section: Main Script
echo "upgrading 4" > /tmp/fw_update_status
##
echo "" > /tmp/update.log
deviceid=`awk -F= '{if($1=="DEVICEID") {gsub(/"/,"",$2); print $2}}' /var/www/rest-api/config/dynamicconfig.ini`
[ -f /tmp/update_url ] && auto=1    
update_log "preinst: id=${deviceid} auto=$auto"


if [ "${isImage}" == "true" ]; then
    if [ "${currentRootDevice}" == "/dev/md0" ]; then
       upgradeDevice="/dev/md1"
    else
       upgradeDevice="/dev/md0"
    fi
    ## special case for ITR 84541.  If forked-daapd is not killed at this point, then force it with kill -9
	killall -9 forked-daapd

	# disable lazy init during update if image
	if [ ! -z "$dataVolumeLazyInitMountOpt" ]; then
		echo "disable lazy init"
		## disable lazy init during update to keep from disk thrashing
		mount -o remount,noinit_itable $dataVolumeDevice
	fi        

    # make sure raid mirror is fully intact before begining the update	
    restoreRaid "wait"
    # breakRaid if image
    
    update_log "preinst: break raid"
    breakRaid
    # setup a mount path for the upgrade device
    upgradePath=/mnt/rootfs
fi
##
echo "Preparing FW upgrade image on: \"${upgradeDevice}\""
touch /etc/.fw_update_fail_check
sync
##
echo "${upgradePath}"       > /tmp/upgrade_path
echo "${upgradePart}"       > /tmp/upgrade_part
echo "${upgradeDevice}"     > /tmp/upgrade_device
echo "${currentRootDevice}" > /tmp/currentRootDevice
echo "upgrading 10"         > /tmp/fw_update_status
##
echo "preinst: currentRootDevice=${currentRootDevice}"
echo "preinst: upgradePath=${upgradePath}"
echo "preinst: upgradePart=${upgradePart}"
echo "preinst: upgradeDevice=${upgradeDevice}"
sync 

update_log "preinst: currentRootDevice=${currentRootDevice} upgradePath=${upgradePath} upgradePart=${upgradePart} upgradeDevice=${upgradeDevice}"
send_update_log

##
if [ ! -f /tmp/downgrade ]; then 
    start_timeout
fi
echo "Unpacking.."

