#!/usr/bin/env bash
# Expose local nginx (:80) via Cloudflare Tunnel (public URL from SUITE_ORIGIN in .env).
set -euo pipefail

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

if [[ ! -f .env ]]; then
  echo "Missing .env — run: cp .env.example .env" >&2
  exit 1
fi

RESOLVED="$(mktemp)"
trap 'rm -f "$RESOLVED"' EXIT

if command -v go >/dev/null 2>&1; then
  go run ./cmd/envexpand -in .env -out "$RESOLVED"
else
  if [[ -x ./bin/envexpand ]]; then
    ./bin/envexpand -in .env -out "$RESOLVED"
  else
    echo "Go not found — install Go or build: go build -o bin/envexpand ./cmd/envexpand" >&2
    exit 1
  fi
fi

set -a
# shellcheck disable=SC1091
source "$RESOLVED"
set +a

if [[ -z "${CLOUDFLARE_TUNNEL_TOKEN:-}" ]]; then
  echo "CLOUDFLARE_TUNNEL_TOKEN is not set in .env" >&2
  exit 1
fi

PUBLIC_URL="${CLOUDFLARE_TUNNEL_PUBLIC_URL:-${SUITE_ORIGIN:-http://localhost}}"
echo "Cloudflare tunnel → local stack (nginx :80)"
echo "Public URL: ${PUBLIC_URL}"
echo "Start stack first: ./deploy/compose-up.sh up -d"

exec cloudflared tunnel --loglevel error run --token "$CLOUDFLARE_TUNNEL_TOKEN"
