#!/bin/sh
set -eu

SCRIPT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
APP_DIR=$(CDPATH= cd -- "$SCRIPT_DIR/.." && pwd)
CONFIG_PATH=${1:-"$APP_DIR/router_local.conf"}

if [ ! -r "$CONFIG_PATH" ]; then
  echo "[router-http] config not found: $CONFIG_PATH" >&2
  exit 1
fi

# shellcheck disable=SC1090
. "$CONFIG_PATH"

BUSYBOX_BIN=${BUSYBOX_BIN:-"$APP_DIR/busybox_armv7l"}
RUNTIME_DIR=${RUNTIME_DIR:-"$APP_DIR/cfip_runtime"}
VALUE_TEXT_FILE=${VALUE_TEXT_FILE:-"current_ip.txt"}
HTTP_PORT=${HTTP_PORT:-8080}

TEXT_PATH="$RUNTIME_DIR/$VALUE_TEXT_FILE"
INDEX_PATH="$RUNTIME_DIR/index.html"

resolve_busybox() {
  if [ -n "$BUSYBOX_BIN" ] && [ -x "$BUSYBOX_BIN" ]; then
    printf '%s\n' "$BUSYBOX_BIN"
    return 0
  fi

  if [ -x "$APP_DIR/busybox_armv7l" ]; then
    printf '%s\n' "$APP_DIR/busybox_armv7l"
    return 0
  fi

  if command -v busybox >/dev/null 2>&1; then
    command -v busybox
    return 0
  fi

  return 1
}

busybox_has_applet() {
  busybox_bin="$1"
  applet="$2"
  "$busybox_bin" --list 2>/dev/null | grep "^$applet$" >/dev/null
}

ensure_index() {
  if [ ! -f "$TEXT_PATH" ]; then
    return 0
  fi

  rm -f "$INDEX_PATH"
  cp "$TEXT_PATH" "$INDEX_PATH"
}

start_httpd() {
  busybox_bin=$(resolve_busybox || true)
  if [ -n "$busybox_bin" ] && busybox_has_applet "$busybox_bin" httpd; then
    echo "[router-http] serving $RUNTIME_DIR on 0.0.0.0:$HTTP_PORT via $busybox_bin httpd"
    "$busybox_bin" httpd -f -p "$HTTP_PORT" -h "$RUNTIME_DIR" &
    httpd_pid=$!
    trap 'kill "$httpd_pid" 2>/dev/null || true' INT TERM EXIT
    wait "$httpd_pid"
    exit $?
  fi

  if [ -n "$busybox_bin" ]; then
    echo "[router-http] selected BusyBox has no httpd applet: $busybox_bin" >&2
  fi
  if command -v httpd >/dev/null 2>&1; then
    echo "[router-http] found system httpd at $(command -v httpd), but it is not used" >&2
    echo "[router-http] ASUS firmware httpd is usually the router admin web server and does not support serving an arbitrary -h directory" >&2
  fi

  echo "[router-http] usable BusyBox httpd applet not found" >&2
  echo "[router-http] set BUSYBOX_BIN in router_local.conf to your full BusyBox binary, for example: BUSYBOX_BIN=\"./busybox_armv7l\"" >&2
  exit 1
}

if [ ! -d "$RUNTIME_DIR" ]; then
  echo "[router-http] runtime dir not found: $RUNTIME_DIR" >&2
  echo "[router-http] run: sh scripts/router_local_update.sh $CONFIG_PATH" >&2
  exit 1
fi

ensure_index
start_httpd
