#!/usr/bin/env bash
# Start the local tdc114plus-auth broker with one env file.
# Usage: ./scripts/start-auth-server.sh [--restart] [--env-file=PATH]

set -euo pipefail

ROOT_DIR="$(cd "$(dirname "$0")/.." && pwd)"
AUTH_DIR="${TDC114_AUTH_WORKTREE:-/home/ubuntu/workspace/tdc114plus-auth}"
ENV_FILE="$ROOT_DIR/scripts/.env.android-device.local"
NAVER_WORKS_ENV_FILE="${NAVER_WORKS_ENV_FILE:-$ROOT_DIR/secrets/naver_works_service_account.local.env}"
AUTH_GOCACHE="${AUTH_GOCACHE:-/tmp/tdc114plus-auth-gocache}"
LOG_BASE_DIR="${TDC114_LOG_BASE:-$ROOT_DIR/logs}"
LOG_DIR="$LOG_BASE_DIR/$(date +%F)"
LOG_FILE="$LOG_DIR/tdc114plus-auth.log"
PORT="${TDC114_AUTH_PORT:-5001}"
RESTART=false

for arg in "$@"; do
  case "$arg" in
    --restart) RESTART=true ;;
    --env-file=*) ENV_FILE="${arg#*=}" ;;
    --help|-h)
      cat <<EOF
Usage: $0 [--restart] [--env-file=PATH]

--restart       Stop the current listener on the auth port before starting.
--env-file=PATH Read local test values from this env file.
EOF
      exit 0
      ;;
    *) echo "Unknown arg: $arg" >&2; exit 2 ;;
  esac
done

mkdir -p "$LOG_DIR"
mkdir -p "$AUTH_GOCACHE"

log() {
  echo "$*"
}

fail() {
  echo "FAIL $*" >&2
  exit 1
}

require_file() {
  [ -f "$1" ] || fail "missing file: $1"
}

require_dir() {
  [ -d "$1" ] || fail "missing directory: $1"
}

listener_pids() {
  lsof -nP -iTCP:"$PORT" -sTCP:LISTEN -t 2>/dev/null || true
}

wait_for_health() {
  local i=1
  while [ "$i" -le 20 ]; do
    if curl -fsSL --max-time 2 "http://127.0.0.1:$PORT/health" >/dev/null 2>&1; then
      return 0
    fi
    sleep 0.5
    i=$((i + 1))
  done
  return 1
}

require_dir "$AUTH_DIR"
require_file "$AUTH_DIR/cmd/server/main.go"
require_file "$ENV_FILE"
require_file "$AUTH_DIR/secrets/private_key.pem"
require_file "$AUTH_DIR/secrets/public_key.pem"

current_pids="$(listener_pids)"
if [ -n "$current_pids" ]; then
  if [ "$RESTART" = true ]; then
    log "Stopping existing auth server on :$PORT"
    # shellcheck disable=SC2086
    kill $current_pids 2>/dev/null || true
    sleep 1
  else
    if wait_for_health; then
      log "tdc114plus-auth is already running on :$PORT"
      exit 0
    fi
    fail "port $PORT is already in use, but health check failed. Run with --restart."
  fi
fi

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

if [ -f "$NAVER_WORKS_ENV_FILE" ]; then
  set -a
  # shellcheck source=/dev/null
  source "$NAVER_WORKS_ENV_FILE"
  set +a

  if [ -n "${WORKS_ADMIN_OAUTH_CLIENT_PRIVATE_KEY_FILE:-}" ] && [[ "$WORKS_ADMIN_OAUTH_CLIENT_PRIVATE_KEY_FILE" != /* ]]; then
    WORKS_ADMIN_OAUTH_CLIENT_PRIVATE_KEY_FILE="$ROOT_DIR/$WORKS_ADMIN_OAUTH_CLIENT_PRIVATE_KEY_FILE"
    export WORKS_ADMIN_OAUTH_CLIENT_PRIVATE_KEY_FILE
  fi
fi

ORG_CONTEXT_BASE="${BARON_ORG_CONTEXT_BASE_URL:-${TDC114_ORG_CONTEXT_API_BASE:-}}"
ORG_CONTEXT_TENANT_SLUG="${BARON_ORG_CONTEXT_TENANT_SLUG:-${TDC114_ORG_CONTEXT_TENANT_SLUG:-}}"
ORG_CONTEXT_KEY_ID="${BARON_ORG_CONTEXT_KEY_ID:-${TDC114_BARON_KEY_ID:-}}"
ORG_CONTEXT_KEY_SECRET="${BARON_ORG_CONTEXT_KEY_SECRET:-${TDC114_BARON_KEY_SECRET:-}}"

: "${ORG_CONTEXT_BASE:?BARON_ORG_CONTEXT_BASE_URL is required in $ENV_FILE}"
: "${ORG_CONTEXT_TENANT_SLUG:?BARON_ORG_CONTEXT_TENANT_SLUG is required in $ENV_FILE}"
: "${ORG_CONTEXT_KEY_ID:?BARON_ORG_CONTEXT_KEY_ID is required in $ENV_FILE}"
: "${ORG_CONTEXT_KEY_SECRET:?BARON_ORG_CONTEXT_KEY_SECRET is required in $ENV_FILE}"

UPSTREAM_ORG_CONTEXT_BASE="${TDC114_AUTH_UPSTREAM_ORG_CONTEXT_API_BASE:-}"
if [ -z "$UPSTREAM_ORG_CONTEXT_BASE" ]; then
  UPSTREAM_ORG_CONTEXT_BASE="$ORG_CONTEXT_BASE"
fi

log "Starting tdc114plus-auth on :$PORT"
log "Log file: $LOG_FILE"

(
  cd "$AUTH_DIR"
  setsid env \
    GOCACHE="$AUTH_GOCACHE" \
    PORT="$PORT" \
    AUTH_PROVIDER=baron \
    APP_SESSION_SECRET="${APP_SESSION_SECRET:-tdc114plus-dev-session}" \
    BARON_BASE_URL="${BARON_BASE_URL:-https://sso.hmac.kr}" \
    BARON_CLIENT_ID="${BARON_CLIENT_ID:-243f0b04-a417-4fbe-ae59-a90b16783a79}" \
    BARON_OIDC_AUTHORIZATION_URL="${BARON_OIDC_AUTHORIZATION_URL:-https://sso.hmac.kr/oidc/oauth2/auth}" \
    BARON_OIDC_TOKEN_URL="${BARON_OIDC_TOKEN_URL:-https://sso.hmac.kr/oidc/oauth2/token}" \
    BARON_OIDC_REDIRECT_URI="${BARON_OIDC_REDIRECT_URI:-https://114-auth.hmac.kr/api/v1/auth/oidc/callback}" \
    BARON_OIDC_SCOPES="${BARON_OIDC_SCOPES:-openid profile email}" \
    BARON_PRIVATE_KEY_PATH="${BARON_PRIVATE_KEY_PATH:-./secrets/private_key.pem}" \
    BARON_PUBLIC_KEY_PATH="${BARON_PUBLIC_KEY_PATH:-./secrets/public_key.pem}" \
    BARON_JWKS_KID="${BARON_JWKS_KID:-tdc114plus-auth-key-1}" \
    BARON_LINK_RETURN_URI="${BARON_LINK_RETURN_URI:-}" \
    BARON_ORG_CONTEXT_BASE_URL="$UPSTREAM_ORG_CONTEXT_BASE" \
    BARON_ORG_CONTEXT_TENANT_SLUG="$ORG_CONTEXT_TENANT_SLUG" \
    BARON_ORG_CONTEXT_KEY_ID="$ORG_CONTEXT_KEY_ID" \
    BARON_ORG_CONTEXT_KEY_SECRET="$ORG_CONTEXT_KEY_SECRET" \
    go run ./cmd/server >>"$LOG_FILE" 2>&1 < /dev/null &
)

if ! wait_for_health; then
  tail -n 80 "$LOG_FILE" >&2 || true
  fail "tdc114plus-auth did not become healthy on :$PORT"
fi

log "tdc114plus-auth ready on :$PORT"
