#!/usr/bin/env bash

set -euo pipefail

WEB_ROOT=${1:-/opt/lingniu-vehicle-platform/current/web}
BASE_URL=${2:-http://127.0.0.1:20300}
PREVIOUS_MANIFEST=${3:-}
CURL_TIMEOUT_SEC=${CURL_TIMEOUT_SEC:-15}

BASE_URL=${BASE_URL%/}
CURRENT_MANIFEST="$WEB_ROOT/.release-assets"
response_file=$(mktemp)
trap 'rm -f "$response_file"' EXIT

fail() {
  printf 'web release smoke failed: %s\n' "$*" >&2
  exit 1
}

fetch_exact() {
  local url_path=$1
  local expected_file=$2
  local label=$3
  local status

  test -f "$expected_file" || fail "$label is missing on disk: $expected_file"
  status=$(curl --silent --show-error --max-time "$CURL_TIMEOUT_SEC" --output "$response_file" --write-out '%{http_code}' "$BASE_URL$url_path" || true)
  test "$status" = 200 || fail "$label returned HTTP ${status:-000}: $url_path"
  cmp -s "$expected_file" "$response_file" || fail "$label response differs from release file: $url_path"
}

verify_manifest() {
  local manifest=$1
  local kind=$2
  local count=0
  local asset

  test -f "$manifest" || fail "$kind manifest is missing: $manifest"
  while IFS= read -r asset || test -n "$asset"; do
    asset=${asset%$'\r'}
    test -n "$asset" || continue
    case "$asset" in
      /*|*../*|../*|*/..|..)
        fail "$kind manifest contains unsafe asset path: $asset"
        ;;
    esac
    fetch_exact "/assets/$asset" "$WEB_ROOT/assets/$asset" "$kind asset"
    count=$((count + 1))
  done < "$manifest"
  test "$count" -gt 0 || fail "$kind manifest is empty: $manifest"
  printf '%s' "$count"
}

fetch_exact / "$WEB_ROOT/index.html" 'root document'

config_status=$(curl --silent --show-error --max-time "$CURL_TIMEOUT_SEC" --output "$response_file" --write-out '%{http_code}' "$BASE_URL/app-config.js" || true)
test "$config_status" = 200 || fail "app config returned HTTP ${config_status:-000}"
grep -q 'window\.__LINGNIU_APP_CONFIG__' "$response_file" || fail 'app config response does not expose the runtime configuration object'
if grep -q '"amapSecurityJsCode"' "$response_file"; then
  fail 'app config response exposes the server-side AMap security code'
fi
grep -q '"amapSecurityServiceHost":"/_AMapService"' "$response_file" || fail 'app config response does not enable the server-side AMap proxy'

current_count=$(verify_manifest "$CURRENT_MANIFEST" current)
compatibility_count=0
if test -n "$PREVIOUS_MANIFEST"; then
  compatibility_count=$(verify_manifest "$PREVIOUS_MANIFEST" compatibility)
fi

printf 'web_release_smoke=ok current_assets=%s compatibility_assets=%s\n' "$current_count" "$compatibility_count"
