#!/bin/bash
# bom update utilities
upgradePath=${2:-"/"}
. ${upgradePath}/etc/system.conf 2>/dev/null
firmwareUpdateFailed=${firmwareUpdateFailed:-"1003"}

error_exit ()
{
    logger -s "${logtag} Failed package installation phase: ${pkg_version} `date`"
    sendAlert.sh "ALERT=${firmwareUpdateFailed}";
    exit 1
}

# restore raid $1 == wait to wait
restoreRaid ()
{
    currentRootDevice=`cat /proc/cmdline | awk -F= 'BEGIN{RS=" "}{ if ($1=="root") print $2 }'`
    duplicate_md=
    if [ "${currentRootDevice}" != "/dev/nfs" ]; then

        # Stop lazy init if currently active on DataVolume
        mount | grep -q $dataVolumeDevice
        mount_status=$?
        if [ $mount_status -eq 0 ] && [ ! -z "$dataVolumeLazyInitMountOpt" ]; then
            logger -s "disable lazy init"
            ## disable lazy init during raid restore
            mount -o remount,noinit_itable $dataVolumeDevice
        fi

        # Stop any duplicate md devices. Make sure both disks are part of the current rootfs md device
        if [ "${currentRootDevice}" == "/dev/md0" ]; then
            if [ -e /dev/md1 ]; then
                duplicate_md="/dev/md1"
            fi
        elif [ "${currentRootDevice}" == "/dev/md1" ]; then
            if [ -e /dev/md0 ]; then
                duplicate_md="/dev/md0"
            fi
        fi
        if [ ! -z ${duplicate_md} ]; then
            echo "stopping duplicate md device ${duplicate_md}"
            mdadm --stop ${duplicate_md} 2>/dev/null
            mdadm --wait ${duplicate_md} 2>/dev/null
            rm -rf ${duplicate_md}
            sleep 1
        fi
        
        # always attempt to add all mirror partitions - its ok to fail if they are already there
        # "--remove" will only remove failed disks, and is necessary to allow "--add" them for
        # resyncing the array; in a standalone program, use the following to identify failed disks
        # mdadm --detail "${currentRootDevice}" | sed -n -e '/faulty/s#\(.*\)\(/dev/.*\)#\2#p'
        devices=(`internalDrives`)
        for (( i=0; i<${#devices[@]}; i++ )); do
            restoreDevice="${devices[$i]}1"
            echo "Restore raid device: $restoreDevice"
            mdadm ${currentRootDevice} --remove ${restoreDevice} > /dev/null 2>&1
            mdadm --wait ${currentRootDevice} 
            mdadm ${currentRootDevice} --add ${restoreDevice} > /dev/null 2>&1
            [ "$1" == "wait" ] && mdadm --wait ${currentRootDevice} 
            
            restoreDevice="${devices[$i]}2"
            echo "Restore raid device: $restoreDevice"
            mdadm ${currentRootDevice} --remove ${restoreDevice} > /dev/null 2>&1
            mdadm ${currentRootDevice} --add ${restoreDevice} > /dev/null 2>&1
            [ "$1" == "wait" ] && mdadm --wait ${currentRootDevice} 
        done
        sleep 1
        
        # Resume lazy inits on DataVolume
        if [ $mount_status -eq 0 ] && [ ! -z "$dataVolumeLazyInitMountOpt" ]; then
            mount -o remount,$dataVolumeLazyInitMountOpt $dataVolumeDevice
        fi
    fi
}

bom_oldpkg ()
{
    ## check current package status
    uplog "update_utilities: bom_oldpkg($@)"
    pkgname=${1}

    pkgstate=$(dpkg -l | grep ${pkgname} | cut -f1 -d' ')
    uplog "package state: ${pkgstate}"
    echo "pkgstate_${pkgstate}=${pkgstate}" >> ${pkg_upgrades_dir}/${pkgname}_pkgstate
}

# post entries to updatelog
updatelog="/CacheVolume/update.log"

uplog()
{
    logtext=${@}
    logtag="`basename $0`:`date -u +"%D %T"`:"
    echo "${logtag}${logtext}" >> ${updatelog}
    logger -s "${logtag}${logtext}"
}

## Section: Functions
quit()
{
    echo ERROR: $1
    exit 1
}

printUsage()
{
    echo "usage: projectInstall.sh <rfs_dir> <project_control_file>"
}

