#!/bin/sh
VERSION="${1}"
if [ $(cat /lib/gluon/release) = "${VERSION}" ]; then
    echo "Version ${VERSION} is already installed."
    exit 5
fi
IMAGE=$(lua -e 'print(require("platform_info").get_image_name())')
MANIFEST=$(wget -q -O- "http://firmware.ffnw.de/l2tp/${VERSION}/sysupgrade/stable.manifest" | awk "\$1 == \"${IMAGE}\" && length(\$3) == 64 { printf(\"%s %s\\n\", \$3, \$NF); exit }") || exit 1
SHA256=$(echo "${MANIFEST}" | awk '{print $1}') || exit 1
FILE=$(echo "${MANIFEST}" | awk '{print $2}') || exit 1
wget -O /tmp/fw.bin http://firmware.ffnw.de/l2tp/${VERSION}/sysupgrade/${FILE} || exit 1
echo "${SHA256}  /tmp/fw.bin" | sha256sum -c - || exit 2
batctl gwl | awk '$1 == "*" && $2 == $4 { exit 42 }' || sleep 60 || exit 3
sysupgrade /tmp/fw.bin || exit 4
