#!/bin/sh

usage() {
    echo "Usage: $0 -a <device> <id> <mountpoint>"
    echo "       $0 -h"
}

APPDEV=
DIAGDEV=

# script is called as flasher-netbird/flasher-netbold/flesher-netbox
# split $0 up at '-' to get the profile:
PROFILE=${0##*-}

while getopts ":a:d:h" o; do
    case "${o}" in
        a)
            APPDEV=${OPTARG}
            ;;
        d)
            DIAGDEV=${OPTARG}
            ;;
        h)
            usage
            exit 0;
            ;;
        *)
            usage >&2
            exit 1;
    esac
done
shift $((OPTIND-1))

if [ $# -ne 2 ]; then
    usage >&2
    exit 1
fi

DEV_ID=$1
MNT=$(dirname $2)

STTY_OPTIONS="115200 crtscts -brkint -icrnl -imaxbel -opost -onlcr -isig -icanon -iexten \
              -ixon -echo -echoe -echok -echoctl -echoke min 1 time 0 \
              intr undef quit undef erase undef kill undef eof undef eol undef eol2 undef swtch undef \
              start undef stop undef susp undef rprnt undef werase undef lnext undef flush undef
             "

if [ -z ${APPDEV} ] || [ -z ${DIAGDEV} ] || [ -z ${DEV_ID} ] || [ -z ${MNT} ]; then
    usage >&2
    exit 1
fi

USB_DEVICE=$(cat /proc/sysinfo/wwan${DEV_ID}/usbName)

logger "Using devices ${USB_DEVICE} ${APPDEV} ${DIAGDEV} for module wwan${DEV_ID}"

source ${MNT}/target

stty -F ${APPDEV} ${STTY_OPTIONS}
echo "ATI4" | ${MNT}/atinout-${PROFILE} - ${APPDEV} - |grep -q "${TARGET}"
if [ $? -ne 0 ]; then
    logger -p ERROR "Firmware is not intended for this modem (wwan${DEV_ID}) or could not read modem type. Expected modem: '${TARGET}'"
    exit 1
fi

${MNT}/uxfp --file ${MNT}/firmware --port ${DIAGDEV}
RES=$?
if [ $RES -ne 0 ] ; then
    logger "Update of module wwan${DEV_ID} failed! Error: ${RES}"
    exit 1
fi

logger "Waiting for module wwan${DEV_ID} to restart"
for i in $(seq 120); do
    if [ -e  /sys/bus/usb/devices/${USB_DEVICE}:1.5 ]; then
        logger "Module wwan${DEV_ID} restarted"
        break
    fi
    sleep 1
done

#module needs some time after ttys pop up until it responds again
#(seems to be extremely long with current beta firmware
#check with final firmware if we can reduce this)
sleep 60

logger "Shutting down module wwan${DEV_ID}"
stty -F ${APPDEV} ${STTY_OPTIONS}
echo "AT#SHDN" | ${MNT}/atinout-${PROFILE} - ${APPDEV} -

logger "Waiting for module wwan${DEV_ID} to turn off"
for i in $(seq 120); do
    if [ ! -e  /sys/bus/usb/devices/${USB_DEVICE}:1.5 ]; then
        logger "Module wwan${DEV_ID} turned off"
        break
    fi
    sleep 1
done

logger "Module update finished wwan${DEV_ID}"

exit 0

