#!/bin/sh

CARD=0
MODEM="wwan$CARD"
LEDCNT=$(cat /proc/sysinfo/pd/led  | wc -l)
MAX_LED_IDX=$(expr $LEDCNT - 1)

log()
{
    logger -s -p "local1.notice" -t "autorun" "$*"
}

error()
{
    logger -s -p "local1.error" -t "autorun" "$*"
}

die()
{
    error "$*"
    log "rebooting in 1min"
    reboot -d 60
    exit 1
}

ledstart()
{
    for i in $(seq 0 $MAX_LED_IDX); do
        echo "SLOW YELLOW" > /tmp/status/led-manager/led$i
    done
    sleep 1
}
ledsucc()
{
    for i in $(seq 0 $MAX_LED_IDX); do
        echo "SOLID GREEN" > /tmp/status/led-manager/led$i
    done
    sleep 1
}

ledstop()
{
    for i in $(seq 0 $MAX_LED_IDX); do
        rm -f /tmp/status/led-manager/led$i
    done
    sleep 1
}

ledfail()
{
    for i in $(seq 0 $MAX_LED_IDX); do
        echo "SOLID RED" > /tmp/status/led-manager/led$i
    done
    sleep 1
}

if [ "x$MNTPATH" = "x" ]; then
    ledfail
    die "no mountpath given"
fi

# signal start
ledstart

VERSION=$(cat /proc/sysinfo/releaseVersion)
CONF=""

if [ "$VERSION" = "99.99.99.1" ]; then
    log "updater image running, nothing to do"
    exit 0
fi

# check modem provider config
for i in $(seq 0 6); do
    log "getting firmware info of $MODEM ($i)"
    wwan-cmd $CARD 'AT!IMPREF?'  > /tmp/output 2>&1
    grep -q "^OK" /tmp/output && break;
    sleep 5
done
CONF=$(grep "current config name: " /tmp/output | awk -F ':' '{ print $2; }' | sed 's/ //g')

if [ "$CONF" != "TELSTRA_002.019_001" ]; then
    log "firmware of $MODEM is NOK ($CONF)"

    if [ ! -e "$MNTPATH/mc74xx-updater" ]; then
        log "no updater found"
        ledfail
        exit 1
    fi

    log "installing $MNTPATH/mc74xx-updater"
    /usr/local/sbin/update-software -fr "$MNTPATH/mc74xx-updater"
    exit 0
fi

log "firmware of $MODEM is OK ($CONF)"

# signal success
ledsucc
sleep 15
ledstop

exit 0
