#!/usr/bin/env bash
set -euo pipefail

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
PUBLISH_DIR="$ROOT_DIR/src/Ehwrj.App/bin/Release/net8.0/win-x64/publish"
ARTIFACT_DIR="$ROOT_DIR/artifacts"
PACKAGE_DIR="$ARTIFACT_DIR/ehwrj-win-x64"
ZIP_PATH="$ARTIFACT_DIR/ehwrj-win-x64.zip"

while [[ $# -gt 0 ]]; do
  case "$1" in
    --publish-dir)
      PUBLISH_DIR="$2"
      shift 2
      ;;
    --zip)
      ZIP_PATH="$2"
      ARTIFACT_DIR="$(dirname "$ZIP_PATH")"
      PACKAGE_DIR="$ARTIFACT_DIR/ehwrj-win-x64"
      shift 2
      ;;
    -h|--help)
      cat <<'EOF'
Usage:
  scripts/package-win-x64.sh [--publish-dir path] [--zip path]

Creates a portable Windows x64 ZIP containing Ehwrj.exe, native DLLs,
README, SECURITY, LICENSE, RUNNING.txt, and SHA256SUMS.txt.
EOF
      exit 0
      ;;
    *)
      echo "error: unknown argument: $1" >&2
      exit 2
      ;;
  esac
done

if [[ ! -x "$PUBLISH_DIR/Ehwrj.exe" ]]; then
  echo "error: missing published Ehwrj.exe; run scripts/publish-win-x64.sh first." >&2
  exit 1
fi

rm -rf "$PACKAGE_DIR"
mkdir -p "$PACKAGE_DIR"

cp "$PUBLISH_DIR/Ehwrj.exe" "$PACKAGE_DIR/"
cp "$PUBLISH_DIR"/*.dll "$PACKAGE_DIR/"
cp "$ROOT_DIR/README.md" "$PACKAGE_DIR/README.md"
cp "$ROOT_DIR/SECURITY.md" "$PACKAGE_DIR/SECURITY.md"
cp "$ROOT_DIR/LICENSE" "$PACKAGE_DIR/LICENSE"

cat > "$PACKAGE_DIR/RUNNING.txt" <<'EOF'
Ehwrj portable Windows x64 build

1. Start War Thunder.
2. Confirm the local map is available at http://127.0.0.1:8111/map_info.json.
3. Run Ehwrj.exe.
4. Use "Show overlay" in the left panel to enable the click-through overlay.

Network scope:
- Ehwrj only reads the loopback War Thunder local API.
- It does not contact external hosts.

Settings:
- Saved under %LOCALAPPDATA%\Ehwrj\settings.json.
EOF

(
  cd "$PACKAGE_DIR"
  sha256sum * > SHA256SUMS.txt
)

rm -f "$ZIP_PATH"
(
  cd "$ARTIFACT_DIR"
  zip -qr "$(basename "$ZIP_PATH")" "$(basename "$PACKAGE_DIR")"
)

echo "$ZIP_PATH"
