#!/bin/bash
set -euo pipefail
umask 077

ROOT=$(CDPATH='' cd -- "$(dirname -- "$0")/.." && pwd)
cd "$ROOT"

ENV_FILE="$ROOT/.env"

if [[ ! -f "$ENV_FILE" ]]; then
  echo "Missing $ENV_FILE." >&2
  exit 1
fi

set -a
# shellcheck source=/dev/null
. "$ENV_FILE"
set +a

: "${PHX_HOST:?PHX_HOST is missing from .env}"
: "${PHX_SCHEME:?PHX_SCHEME is missing from .env}"
: "${PHX_URL_PORT:?PHX_URL_PORT is missing from .env}"

if [[ "$PHX_SCHEME" != https ]]; then
  echo "The PWA browser check requires PHX_SCHEME=https." >&2
  exit 1
fi

base_url="${PHX_SCHEME}://${PHX_HOST}"

if [[ "$PHX_URL_PORT" != 443 ]]; then
  base_url="${base_url}:${PHX_URL_PORT}"
fi

run_id="$(date -u +%Y%m%d%H%M%S)-$$"
output_dir="$ROOT/output/staging-pwa-e2e/$run_id"
mkdir -p "$output_dir"
chmod 700 "$ROOT/output" "$ROOT/output/staging-pwa-e2e" "$output_dir"

curl --fail --silent --show-error "$base_url/healthz/ready" \
  >"$output_dir/public-ready.json"
curl --fail --silent --show-error "$base_url/sw.js" \
  >"$output_dir/public-service-worker.js"
curl --fail --silent --show-error "$base_url/manifest.webmanifest" \
  >"$output_dir/public-manifest.webmanifest"

docker build --tag who-need-help-e2e-tests:local e2e \
  >"$output_dir/browser-build.log"

docker run --rm \
  --network host \
  --user "$(id -u):$(id -g)" \
  --env "BASE_URL=$base_url" \
  --env HOME=/tmp \
  --volume "$output_dir:/work/output" \
  who-need-help-e2e-tests:local \
  npx playwright test --config=playwright.pwa.config.ts

echo "Public HTTPS PWA verification passed: $base_url"
echo "Evidence: $output_dir"
