#!/bin/bash
logger -s "## postinst_all ##"

now="`date`"
echo "Setting update date to current date: ${now}"
date +%s > ${upgradePath}/etc/version.update

if [ -f /tmp/downgrade ]; then
	settings_mgr=/usr/local/sbin/settingsManager.sh
	
	logger -s "add post boot script to fix swapsize"
	fixpg_boot_file="${upgradePath}/etc/wdcomp.d/boot/bootscript_001_fixswap"
	echo "#!/bin/bash" > $fixpg_boot_file
	echo "swapon --fixpgsz /dev/sda3" >> $fixpg_boot_file
	chmod 777 $fixpg_boot_file
else
	settings_mgr=${upgradePath}/usr/local/sbin/settingsManager.sh
fi

## Manage saved settings and indicate "updateInProgress" on next boot
## TODO: remove outer conditional (below) when pkg manager is no longer used by fresh-install process

if [ ! -f /tmp/fresh_install ]; then
##

    if [ -f /tmp/fresh_update ]; then
        logger -s "Fresh state detected"
        # copy master_drive_serial_number and reformat the DataVolume for 'fresh update'
        echo "${dataVolumeFormat}" > ${upgradePath}/${reformatDataVolume}
        cp -v /var/log/master_drive_serial_number ${upgradePath}/var/log/master_drive_serial_number 2>/dev/null
        # notify system about "fresh" condition on reboot
        factoryRestore.sh
        touch ${upgradePath}/etc/.fresh_install
        # Force the kernel and control partion copying here for now...
        # TODO: Use separate kernel and image containers deployed by common group container.
        # "Why?" For one, the ugly dependency directly below V here V to a project specific module name which currently must be hard coded into the top-level postinst.
        ${settings_mgr} -p kernel-mindspeed-sequoia --action update --upgradepath "${upgradePath}"
    else
        logger -s "Upgrade state detected"
        if [ ! -f /tmp/fresh_update ]; then
            ## manage saved settings for master-package ##
            if [ -n "${upgradeDevice}" ]; then
                ${settings_mgr} --action update --upgradepath "${upgradePath}"
            fi
            ## Indicate fw update on re-boot
            touch ${upgradePath}/etc/.updateInProgress
        fi
    fi

##
fi

## Save cached debs accross factory-restore
if [ -d ${pkg_upgrades_dir} ]; then
    logger -s "Saving upgrade cache to redundant location in rootfs"
    echo "Saving upgrade cache to redundant location in rootfs" >> /CacheVolume/update.log
    rm -rf ${upgradePath}/usr/local/nas/upgrade/* #*/
    mkdir -p ${upgradePath}/usr/local/nas/upgrade
    cp -rpvf ${pkg_upgrades_dir}/* ${upgradePath}/usr/local/nas/upgrade >> /CacheVolume/update.log #*/ 
fi

sync
sleep 1

