#!/bin/sh
# Disabled by default.
# To enable:
#   touch '/etc/init.d/stored-fw'  # and reboot
# To disable:
#   rm '/etc/init.d/stored-fw'     # and reboot

[ -e '/etc/init.d/stored-fw' ] || exit 0

FWPATH='/home/martem/fw'

move() {
    read ver 2>/dev/null < '/usr/local/etc/telem/version'
    F="$(
        ls -1 \
        '/mnt/sd/gwupd_done/Telem'*.7z \
        '/root/gwupd_done/Telem'*.7z \
        '/home/martem/gwupd_done/Telem'*.7z \
        2>/dev/null \
        | grep -F -- "_${ver}_" | head -n1
    )"
    
    [ -r "${F}" ] || return
    # Can read 7z file    
    grep -iq -- ' Reload setup' "${F%/*}/res.txt" || return
    # Looks like sucessful update
    
    rm "${FWPATH}/"*.7z	
    mkdir -p "${FWPATH}/"
    mv "${F}" "${FWPATH}/"
    chown martem "${FWPATH}/"
    chown martem "${FWPATH}/"*.7z
}

dynmot() {
    # Output:
    #   stored_fw=y: Device expects GWS to provide 7z firmware file
    #   stored_fw=path: same as previous, path tells current 7z file stored.
    printf "stored_fw="
    {
        ls -1 "${FWPATH}/Telem"*.7z
        echo y
    } 2>/dev/null \
    | head -n 1
}

start() {
    move 2>/dev/null

    mkdir -p '/tmp/telem/'
    dynmot > '/tmp/telem/stored_fw'
    chmod +r '/tmp/telem/stored_fw'

    return 0
}

stop() {
    return 0
}

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