#!/bin/sh

. /usr/local/bin/telem/functions

GWUPD_DL=/root/gwupd.dltmp

# temp directory, also lockdir
TEMP=/tmp/fetch-update.tmp
LOCKDIR="$TEMP"
FETCH=no
METHOD=WGET
ADDRESS=http://phobos.martem.ee/shr/update
CATEGORY="stable"

PHP_API=http://phobos.martem.ee/sw/api.php
#?format=txt

NAME="$(cat /sys/class/net/eth0/address | sed 's/://g')"


mkdir "$LOCKDIR" || {
    logger -s -p "user.info" -t "$0" "Already running";
    exit 1
}


echo $$ > "$LOCKDIR/pid"


[ -f /etc/update.conf ] && . /etc/update.conf

[ "$FETCH" != "yes" ] && {
    rm -rf "$LOCKDIR"
    exit 0
}

update(){
    web_path="$1"
    mkdir -p "$GWUPD_DL"
    wget -P "$GWUPD_DL" "$web_path/VER_STR"

    res=$?
    if [ $res != 0 ]; then
        logger -s -p "user.info" -t "$0" "Did not find update"
        rm -rf "$GWUPD_DL"
        return 2
    fi

    logger -s -p "user.info" -t "$0" "Found version '$(cat "$GWUPD_DL/VER_STR")'"

    if [ "$(cat "$GWUPD_DL/VER_STR")" != "$(cat /usr/local/etc/telem/version)" ]; then
        touch /var/local/telem/errors/fetch-update
        wget -P    "$GWUPD_DL" "$web_path/md5sums"
        wget -c -P "$GWUPD_DL" "$web_path/upd.tar"
        cd "$GWUPD_DL"
        md5sum -c md5sums && mdsums="ok"
        rm -rf /root/{gwupd,gwupd_done}
        mv "$GWUPD_DL" /root/gwupd
        if [ "_$mdsums" == "_ok" ]; then
            rm -rf "$LOCKDIR"
            Reboot
            exit 0
        fi
    fi

    rm -rf "$GWUPD_DL"

    return 1
}

start() {

    case $METHOD in
        WGET)
            # check if custom firmware for device exists
            web_dir="$ADDRESS/custom/$NAME"
            update "$web_dir"
            rm -rf "$LOCKDIR"
            ;;
        PHPAPI)
            # fetch update list
            barcode="$(cat /usr/local/etc/telem/product_id)"
            if [ "_$barcode" != "_" ]; then
                barcode_html="&barcode=$barcode"
            fi  
            wget "$PHP_API?q=latest&format=gwupd&category=$CATEGORY&product=$(cat /usr/local/etc/telem/product)&cpu=$(cat /tmp/telem/board/board)&currentversion=$(cat /usr/local/etc/telem/version)$barcode_html" -O "$TEMP/latest.txt"

            web_dir="$(cat "$TEMP/latest.txt")"

            update "$web_dir"
            rm -rf "$LOCKDIR"
            ;;
        *)
            logger -s -p "user.info" -t "$0" "Unknown method"
            rm -rf "$LOCKDIR"
            exit 1
            ;;
    esac
}
stop() {
    return 0
}
restart() {
    return 0
}

case "$1" in
  start)
    start
    ;;
  force)
    start
    ;;
  stop)
    stop
    ;;
  restart|reload)
    restart
    ;;
  *)
    echo "Usage: $0 {start|stop|restart|force}"
    exit 1
esac

exit $?
