#!/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

METHOD="${REQUEST_METHOD:-GET}"

json_ok() {
  echo "Status: 200 OK"
  echo "Content-Type: application/json"
  echo "Cache-Control: no-store"
  echo
  echo "$1"
}

if [ "$METHOD" = "GET" ]; then
  VERSION="$(ubus call system board 2>/dev/null | jsonfilter -e '@.release.version' 2>/dev/null)"
  [ -z "$VERSION" ] && VERSION="unknown"
  json_ok "{\"ok\":true,\"current\":{\"version\":\"$VERSION\"}}"
  exit 0
fi

if [ "$METHOD" != "POST" ]; then
  echo "Status: 405 Method Not Allowed"
  echo "Content-Type: application/json"
  echo
  echo '{"ok":false,"error":"method_not_allowed"}'
  exit 1
fi

# UI sends raw binary firmware with:
# Content-Type: application/octet-stream
# X-Filename: urlencoded firmware filename

UPLOAD_DIR="/tmp"
RAW_NAME="${HTTP_X_FILENAME:-firmware.bin}"
SAFE_NAME="$(printf "%s" "$RAW_NAME" | tr -cd '[:alnum:]._-')"
[ -z "$SAFE_NAME" ] && SAFE_NAME="firmware.bin"
TARGET="$UPLOAD_DIR/$SAFE_NAME"

# Optional: X-Firmware-Version: 1.0.2  or filename like ...-1.0.2.bin
VER="${HTTP_X_FIRMWARE_VERSION:-}"
[ -z "$VER" ] && VER="${HTTP_X_VERSION:-}"
[ -z "$VER" ] && VER="$(printf '%s' "$SAFE_NAME" | sed -n 's/.*\([0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*\).*/\1/p')"

cat > "$TARGET"

if [ ! -s "$TARGET" ]; then
  echo "Status: 400 Bad Request"
  echo "Content-Type: application/json"
  echo
  echo '{"ok":false,"error":"empty_upload"}'
  exit 1
fi

SYSUPGRADE_ARGS=""
case "${HTTP_X_KEEP_SETTINGS}" in
  1|true|yes) SYSUPGRADE_ARGS="-n" ;;
esac

if [ -n "$VER" ]; then
  if type aw_set_product_firmware >/dev/null 2>&1; then
    aw_set_product_firmware "$VER" || true
  else
    _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
fi

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

json_ok "{\"ok\":true,\"message\":\"upgrade_started\",\"file\":\"$TARGET\"}"
