#!/bin/sh
#
# The FM350-GL occasionally resets itself: it disappears from the bus and
# comes back as the same device.  The kernel reports that as a fresh bind of
# USB interface 1.6, which is the marker used here to bring the WAN interface
# back up.
#
# Sourced by the hotplug handler, so "return" and not "exit".
#

FM350_STATE_DIR=${FM350_STATE_DIR:-/tmp}

[ "$ACTION" = 'bind' ] || return 0

case "$PRODUCT" in
    e8d/7126/1|e8d/7127/1) ;;
    *) return 0 ;;
esac

case "$DEVICENAME" in
    *1.6) ;;
    *) return 0 ;;
esac

# A single reset binds several interfaces in a row; only act on the first one.
fm350_stamp="$FM350_STATE_DIR/fm350.crash.ts"
fm350_now=$(cut -d. -f1 /proc/uptime 2>/dev/null)
fm350_last=$(cat "$fm350_stamp" 2>/dev/null)
case "$fm350_now$fm350_last" in
    *[!0-9]*|'') ;;
    *)
        [ $((fm350_now - fm350_last)) -lt 10 ] && return 0
        ;;
esac
[ -n "$fm350_now" ] && echo "$fm350_now" > "$fm350_stamp"

logger -t 'Fibocom FM350' 'has crashed!'

fm350_count=$(cat "$FM350_STATE_DIR/fm350.crashcount" 2>/dev/null)
case "$fm350_count" in
    ''|*[!0-9]*) fm350_count=0 ;;
esac
echo $((fm350_count + 1)) > "$FM350_STATE_DIR/fm350.crashcount"

fm350_iface=$(uci -q show network | sed -n "s/^network\.\([^.]*\)\.proto='atc'\$/\1/p")

if [ -n "$fm350_iface" ]
then
    for fm350_i in $fm350_iface
    do
        logger -t 'Fibocom FM350' "Restarting $fm350_i interface..."
        ifup "$fm350_i"
    done
else
    logger -t 'Fibocom FM350' 'No WAN interface found for ATC protocol!'
fi
