#/bin/sh

BASE_URL="https://openwrt.vendotek.eu/releases/21.02.3/targets/ramips/mt76x8/"
FIRMWARE_FILE="openwrt-snapshot-ramips-mt76x8-hilink_hlk-7628n-squashfs-sysupgrade.bin"
CHECKSUM_FILE="sha256sums"
RELEASE_FILE="version.buildinfo"

OTA_LOCK="/tmp/.ota"
if [ -f "$OTA_LOCK" ]; then
    exit 0
fi
touch $OTA_LOCK


cd /tmp

wget -4 -c --timeout=10 --quiet "${BASE_URL}${RELEASE_FILE}"
if [ $? -ne 0 ] ; then
  echo "Unable to get release file!"
  exit 1
fi

RELEASE_VER="$(cat $RELEASE_FILE)"
echo $RELEASE_VER

mkdir -p /etc/ota

ls -1 "/etc/ota/$RELEASE_VER"
if [ $? -eq 0 ] ; then
  exit 0
fi

wget -4 -c --timeout=10 --quiet "${BASE_URL}${CHECKSUM_FILE}"
if [ $? -ne 0 ] ; then
  echo "Unable to verify checksums!"
  exit 1
fi

CNT=0
while true; do
CNT=$(($CNT + 1))
if [ "$CNT" -gt 3 ] ; then
    echo "Upgrade failed!"
    exit 1
fi

wget -4 -c --timeout=10 --quiet "${BASE_URL}${FIRMWARE_FILE}"
if [ $? -ne 0 ] ; then
  continue
else
  break
fi

done

cat "$CHECKSUM_FILE" | grep "$FIRMWARE_FILE" | sha256sum -c
if [ $? -ne 0 ] ; then
  echo "Wrong checksums!"
  exit 1
fi



if [ -f "$FIRMWARE_FILE" ]; then
    mkdir -p /etc/ota
    echo "$(date +%s)" > "/etc/ota/$RELEASE_VER"
    cd /tmp
    sync && echo 3 > /proc/sys/vm/drop_caches
    sysupgrade -c -q $FIRMWARE_FILE
fi

exit 0
