#!/bin/bash

SYS_VERSION_FILE="/etc/version"
VERSION_FILE="/data/etc/version"
POST_UPGRADE_DIR="/usr/share/post-upgrade"
POST_UPGRADE_NET_SCHEDULED="/data/.post-upgrade-net-scheduled"

LOG="/var/log/post-upgrade.log"


test -n "${OS_VERSION}" || source /etc/init.d/base

hash=$(md5sum ${VERSION_FILE} 2>/dev/null | cut -d ' ' -f 1)
sys_hash=$(md5sum ${SYS_VERSION_FILE} 2>/dev/null | cut -d ' ' -f 1)

test "${hash}" == "${sys_hash}" && exit 0

test -d ${POST_UPGRADE_DIR} || exit 0

function version_gt() {
    if [[ "$1" != "$2" ]] && [[ $(echo -e "$2\n$1" | semver-sort | head -n 1) == "$2" ]]; then
        return 0
    else
        return 1
    fi
}

function run_post_upgrade() {
    unset OS_VERSION
    # ensure compatibility with previous lowercase os_version
    version="$(source ${VERSION_FILE} 2>/dev/null && echo ${OS_VERSION}${os_version})"
    
    sys_version="$(source ${SYS_VERSION_FILE} 2>/dev/null && echo ${OS_VERSION})"

    echo "---- post-upgrade from ${version} to ${sys_version} ----" >> ${LOG}

    echo -n > ${POST_UPGRADE_NET_SCHEDULED}
    
    versions=$(ls -1 ${POST_UPGRADE_DIR} | rev | cut -d '.' -f 2-100 | rev)
    for v in ${versions}; do
        if [[ ${v} == "post-upgrade" ]]; then
            continue
        fi

        if [[ ${v} == *-net ]]; then  # scripts that require network
            echo "${POST_UPGRADE_DIR}/${v}.sh" >> ${POST_UPGRADE_NET_SCHEDULED}
            continue
        fi
    
        if [[ -z "${version}" ]] || version_gt ${v} ${version}; then
            msg_begin "Post-upgrading to version ${v}"
            ${POST_UPGRADE_DIR}/${v}.sh >> ${LOG} 2>&1
            test $? == 0 && msg_done || msg_fail
        fi
    done
    
    if [[ -x "${POST_UPGRADE_DIR}/post-upgrade.sh" ]]; then
        msg_begin "Running common post-upgrade script"
        ${POST_UPGRADE_DIR}/post-upgrade.sh >> ${LOG} 2>&1
        test $? == 0 && msg_done || msg_fail
    fi
}

case "$1" in
    start)
        run_post_upgrade
        cp ${SYS_VERSION_FILE} ${VERSION_FILE}
        ;;

    stop)
        true
        ;;

    *)
        echo "Usage: $0 {start}"
        exit 1
esac

exit $?
