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

imageDir=${imageDir:-"/CacheVolume/upgrade"}
imageFile=${imageFile:-"${imageDir}/rootfs.img"}
imageMd5=${imageMd5:-"${imageDir}/rootfs.md5"}
blockSize=${blockSize:-"64k"}
blockCount=${blockCount:-"31247"}

echo "Copy image to upgrade device ${upgradeDevice}:"
echo "blockSize=${blockSize} blockCount=${blockCount}"
dd if=${imageFile} of=${upgradeDevice} > /dev/null 2> /dev/null
#
echo "upgrading 70" > /tmp/fw_update_status   
echo "Compare checksum"
sleep 2
sync
dd if=${upgradeDevice} bs=${blockSize} count=${blockCount} 2> /tmp/dderror | md5sum -c ${imageMd5}
checksumOk=$?
echo "ok ${checksumOk}"
#
echo "upgrading 80" > /tmp/fw_update_status
if [ "${checksumOk}" != "0" ]; then
    . /etc/nas/alert-param.sh 2> /dev/null
    firmwareUpdateFailed=${firmwareUpdateFailed:-"1003"}
    echo "Upgrade failed"
    echo "failed 204 \"upgrade copy failure\"" > /tmp/fw_update_status
    # stop the upgrade md device and add disk1 back to the current rootfs md device
    mdadm --stop ${upgradeDevice}
    mdadm --wait ${upgradeDevice}
    sleep 1
    mdadm --zero-superblock --force --verbose ${upgradePart}
    mdadm ${currentRootDevice} --add ${upgradePart}

    sendAlert.sh "${firmwareUpdateFailed}"
    touch /tmp/checksum_failed
    rm -f /etc/.fw_update_fail_check
    exit 0
fi
#===================================
echo "mounting new root file system"
#===================================
mkdir -p ${upgradePath}
mount ${upgradeDevice} ${upgradePath}
sleep 2
# mount
sync
# upgrade partition is now mounted
logger -s "sourcing new config files"
source "${upgradePath}/etc/system.conf" 2>/dev/null
source "${upgradePath}/${install_param}" 2>/dev/null
# remove image files from CacheVolume
rm -f ${imageFile}
rm -f ${imageMd5}
new_version=`cat ${upgradePath}/etc/version`
old_version=`cat /etc/version | tr -d .-`
echo "postinst: old version is ${old_version}"
echo "postinst: new version is ${new_version}"
echo "Saving \"${new_version} `date`\" to /var/log/version.log"
echo "${new_version} `date`" >> /var/log/version.log

