#!/bin/sh
CUR_VERSION=$(cat /barix/info/VERSION)
TMP_UPDATE_DIR="/tmp/firmware_update"

parse_version() {
    local version=$1
    major=$(echo "$version" | cut -d. -f1)
    minor=$(echo "$version" | cut -d. -f2)
    release=$(echo "$version" | cut -d. -f3 | cut -d- -f1)
    # extract what remains after minor version and only accept the format "-devX"
    dev="99999999"
    if echo "$version" | cut -d- -f2 | grep -q '^dev[0-9]\+$'; then
        dev=$(echo $version | cut -d- -f2 | cut -c4-)
    fi
}

is_outdated() {
    parse_version $1
    min_major=$major
    min_minor=$minor
    min_release=$release
    min_dev=$dev

    parse_version $CUR_VERSION
    cur_major=$major
    cur_minor=$minor
    cur_release=$release
    cur_dev=$dev

    if [ $cur_major -eq $min_major ]; then
        if [ $cur_minor -eq $min_minor ]; then
            if [ $cur_release -eq $min_release ]; then
                if [ $cur_dev -ge $min_dev ]; then
                  return 1
                fi
            elif [ $cur_release -gt $min_release ]; then
                return 1
            fi
        elif [ $cur_minor -gt $min_minor ]; then
            return 1
        fi
    elif [ $cur_major -gt $min_major ]; then
        return 1
    fi

    return 0
}

start() {
    MIN_VERSION=$(uci -q get flexa_agent.application.min_fw_version)
    FW_DOWNLOAD_URL=$(uci -q get flexa_agent.application.fw_download_url)

    if [ -n "$MIN_VERSION" ] && is_outdated "$MIN_VERSION"; then
        logger "FLEXA: firmware is outdated! Upgrade to $MIN_VERSION."
        mkdir -p ${TMP_UPDATE_DIR}
        # create file with the url to download the file
        if [ -z "${FW_DOWNLOAD_URL}" ]; then
          FW_DOWNLOAD_URL="http://release.barixupdate.com/signed/ipam400/flexa-2.0/update-core-image-barix-flexa-${MIN_VERSION}.tar"
        fi
        echo "${FW_DOWNLOAD_URL}" > ${TMP_UPDATE_DIR}/update_servers.txt

        # create temporary qiba-update-client conf file
        cp -f /etc/qiba-update-client.conf ${TMP_UPDATE_DIR}/
        jq -rM --arg URL "${TMP_UPDATE_DIR}/update_servers.txt" '. | .updateServers = [$URL]' \
            ${TMP_UPDATE_DIR}/qiba-update-client.conf > ${TMP_UPDATE_DIR}/qiba_update_client-final.conf

        /usr/bin/qiba-update-client -c ${TMP_UPDATE_DIR}/qiba_update_client-final.conf &
    fi
}

stop() {
    echo "nothing to do"
}

case "$1" in
  start)
    start
    ;;
    
  stop)
    stop
    ;;

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

exit 0
