#!/bin/sh

exec 2>&1

RTC_FLAG_FILE=/tmp/rtc_sync

# exit if the htc read only database isn't yet installed
if [ ! -f /usr/local/htc/database/HTC.db ]; then
    exit 1
fi

# check psu-rtc-sync, if present - exit if not successful
if [ -f /etc/sv/psu-rtc-sync/run ]; then
    [[ -f $RTC_FLAG_FILE ]] || exit 1
fi

# call manifest validator if present
if [ -x /usr/bin/manifest_validator.py ]; then
    /usr/bin/manifest_validator.py
fi

# Make sure host manifest is sorted before wifiupdate starts
MANIFEST_PATHNAME=/usr/local/htc/manifest.txt
if [[ -s "$MANIFEST_PATHNAME" ]] ; then
    # Lock to ensure only one process can sort the manifest
    # see https://stackoverflow.com/a/10197327/78947
    if mkdir -- /tmp/manifest_is_sorted ; then
        # Ensure sort order compatible with python and Hanover Central
        export LANG=C
        if ! grep -v  '^#' $MANIFEST_PATHNAME  | sort -C ; then
            echo "Sorting HTC manifest file name $MANIFEST_PATHNAME."
            grep '^#' $MANIFEST_PATHNAME  >$MANIFEST_PATHNAME~
            grep -v '^#' $MANIFEST_PATHNAME  | sort >>$MANIFEST_PATHNAME~
            sync
            mv $MANIFEST_PATHNAME~ $MANIFEST_PATHNAME
        fi
    fi
fi

# copy failure recovery - in case hard power failure while copying database
FLAG_FILE=/htc/copying
TEMPORARY_AREA=/htc/readwrite/tmp/server/HTC-HTCL1
if [ -f ${FLAG_FILE} ]; then
    echo "Copy process was interrupted - attempting recovery from temporary partition"
    # We are just copying enough to get wifiupdate starting - it will then continue the
    # update process to completion (copy files over and upload .DONE flag)

    # The database itself could have been partially copied over, so
    # copying this should be enough to allow it to continue

    cp ${TEMPORARY_AREA}/database/HTC.db /htc/database/
    sync
    echo "Recovery successful"
    rm ${FLAG_FILE}

    echo "Restarting apps"
    sv restart htc
fi

containerpath=/usr/bin/wifiupdate.bin

LANG=en_GB.UTF-8 PYTHONPATH=$containerpath exec python -c'import wifiupdate; wifiupdate.main()' $@
