#!/bin/sh

start() {
    logger -s -p "user.info" -t "$0" "Device booted"

    local STATS_DIR=/var/local/telem/stats

    if [ ! -d "$STATS_DIR" ]; then
        mkdir -p "$STATS_DIR"
    fi

    touch "$STATS_DIR/device-is-booted"

    if [ -e "$STATS_DIR/boot_count" ]; then
        local boot_count="$(cat "$STATS_DIR/boot_count")"

        # increment boot count
        local new_boot_count="$((boot_count + 1))"
    else
        local new_boot_count=1
    fi
    echo "$new_boot_count" > "$STATS_DIR/boot_count"

    if [ -e "$STATS_DIR/boot_count_total" ]; then
        local boot_count="$(cat "$STATS_DIR/boot_count_total")"

        # increment boot count
        local new_boot_count="$((boot_count + 1))"
    else
        local new_boot_count=1
    fi
    echo "$new_boot_count" > "$STATS_DIR/boot_count_total"


    if [ ! -s "$STATS_DIR/app_start_count" ] ; then
        echo "0" > "$STATS_DIR/app_start_count"
    fi

    local FIRMFILE=/var/www/firmware.html

    rm "$FIRMFILE" 2> /dev/null

    product_name="$(cat /usr/local/etc/telem/product)"

    echo -e "<html><head><title>Martem $product_name - Firmware</title></head><body>" > "$FIRMFILE"
    echo -e "<p>$(cat /VERSION)</p>" >> "$FIRMFILE"
    echo -e "<p>$(cat /PACKED)</p>"  >> "$FIRMFILE"
    echo -e "<p>$(uname -a)</p>"     >> "$FIRMFILE"
    echo -e "<p>$(cat /usr/local/etc/telem/version-Telem-GW-git)</p>"       >> "$FIRMFILE"
    echo -e "<p>$(cat /usr/local/etc/telem/version-GwLinux-git)</p>"        >> "$FIRMFILE"
    echo -e "<p>$(grep VERSION= /etc/os-release | sed 's/VERSION=//g')</p>" >> "$FIRMFILE"
    echo -e "</body></html>" >> "$FIRMFILE"

}
stop() {
    return 0
}
restart() {
    return 0
}

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

exit $?
