#!/bin/sh

SCRIPT_DIR="$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)"
. "$SCRIPT_DIR/lib/airwifi-auth.sh"
. "$SCRIPT_DIR/lib/airwifi-firmware-version.sh" 2>/dev/null || . /usr/lib/airwifi/airwifi-firmware-version.sh 2>/dev/null || true

require_auth

json_response() {
  code="$1"
  body="$2"
  echo "Status: $code"
  echo "Content-Type: application/json"
  echo "Cache-Control: no-store"
  echo
  echo "$body"
}

if [ "${REQUEST_METHOD:-GET}" != "POST" ]; then
  json_response "405 Method Not Allowed" '{"ok":false,"error":"method_not_allowed"}'
  exit 1
fi

BODY="$(cat)"
URL="$(printf "%s" "$BODY" | jsonfilter -e '@.download_url' 2>/dev/null)"
KEEP="$(printf "%s" "$BODY" | jsonfilter -e '@.keep_settings' 2>/dev/null)"
SHA256="$(printf "%s" "$BODY" | jsonfilter -e '@.sha256' 2>/dev/null)"
VER="$(printf "%s" "$BODY" | jsonfilter -e '@.version' 2>/dev/null)"
[ -z "$VER" ] && VER="$(printf "%s" "$BODY" | jsonfilter -e '@.latest_version' 2>/dev/null)"
[ -z "$VER" ] && VER="$(printf "%s" "$BODY" | jsonfilter -e '@.version_name' 2>/dev/null)"

if [ -z "$URL" ]; then
  json_response "400 Bad Request" '{"ok":false,"error":"download_url_required"}'
  exit 1
fi

TARGET="/tmp/airwifi-firmware.bin"
if ! wget -q -T 120 -O "$TARGET" "$URL" 2>/dev/null; then
  if ! curl -fsSL -m 120 -o "$TARGET" "$URL" 2>/dev/null; then
    json_response "502 Bad Gateway" '{"ok":false,"error":"download_failed"}'
    exit 0
  fi
fi

if [ ! -s "$TARGET" ]; then
  json_response "400 Bad Request" '{"ok":false,"error":"empty_firmware"}'
  exit 0
fi

if [ -n "$SHA256" ]; then
  HASH="$(sha256sum "$TARGET" 2>/dev/null | awk '{print $1}')"
  if [ -n "$HASH" ] && [ "$HASH" != "$SHA256" ]; then
    rm -f "$TARGET"
    json_response "400 Bad Request" '{"ok":false,"error":"sha256_mismatch"}'
    exit 0
  fi
fi

SYSUPGRADE_ARGS=""
case "$KEEP" in
  true|1|yes) SYSUPGRADE_ARGS="-n" ;;
esac

# Persist product version for Dashboard (survives if settings kept)
if [ -n "$VER" ] && command -v aw_set_product_firmware >/dev/null 2>&1 || type aw_set_product_firmware >/dev/null 2>&1; then
  aw_set_product_firmware "$VER" || true
elif [ -n "$VER" ]; then
  _v="$(printf '%s' "$VER" | sed -n 's/.*\([0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*\).*/\1/p')"
  [ -n "$_v" ] && {
    uci -q set airwifi.info=info
    uci -q set airwifi.info.version="$_v"
    uci -q set airwifi.info.firmware="ivorta OS v${_v}"
    uci -q commit airwifi
  }
fi

(
  sleep 2
  /sbin/sysupgrade $SYSUPGRADE_ARGS "$TARGET" >/tmp/airwifi-upgrade-online.log 2>&1
) &

json_response "200 OK" '{"ok":true,"message":"upgrade_started"}'
