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

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
WEB_DIR="$ROOT_DIR/website"
PORT="${1:-4173}"
PID_FILE="$ROOT_DIR/administration/.offline-server.pid"
LOG_FILE="$ROOT_DIR/administration/.offline-server.log"

if [[ -f "$PID_FILE" ]] && kill -0 "$(cat "$PID_FILE")" 2>/dev/null; then
  echo "Offline server already running on PID $(cat "$PID_FILE")."
  echo "Open: http://127.0.0.1:${PORT}/"
  exit 0
fi

rm -f "$PID_FILE"

ln -sf ikfreunde.com.html "$WEB_DIR/index.html"
nohup python3 -m http.server "$PORT" --bind 127.0.0.1 --directory "$WEB_DIR" >"$LOG_FILE" 2>&1 &
SERVER_PID=$!
echo "$SERVER_PID" > "$PID_FILE"

sleep 0.3
if ! kill -0 "$SERVER_PID" 2>/dev/null; then
  echo "Failed to start offline server on port $PORT."
  echo "Check log: $LOG_FILE"
  rm -f "$PID_FILE"
  exit 1
fi

echo "Offline server started (PID $SERVER_PID)."
echo "Open: http://127.0.0.1:${PORT}/"
echo "Log: $LOG_FILE"
