#!/usr/bin/env bash
# Generate a gitignored docker-compose.override.yml on free host ports, then
# start the stack. Invoked by `make up-local`.
set -euo pipefail

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$ROOT"

COMPOSE="${COMPOSE:-docker compose}"
COMPOSE_OVERRIDE="${COMPOSE_OVERRIDE:-docker-compose.override.yml}"
LOCAL_HTTP_PORT="${LOCAL_HTTP_PORT:-18080}"
LOCAL_HTTPS_PORT="${LOCAL_HTTPS_PORT:-18443}"
LOCAL_POSTGRES_PORT="${LOCAL_POSTGRES_PORT:-15434}"

port_ok() {
  local p="$1"
  if ! lsof -nP -iTCP:"$p" -sTCP:LISTEN >/dev/null 2>&1; then
    return 0
  fi
  # Reuse ports already published by this compose project.
  $COMPOSE port api-gateway 80 2>/dev/null | grep -q ":${p}$" && return 0
  $COMPOSE port api-gateway 443 2>/dev/null | grep -q ":${p}$" && return 0
  $COMPOSE port postgres 5432 2>/dev/null | grep -q ":${p}$" && return 0
  return 1
}

pick() {
  local start="$1" name="$2" p
  for p in $(seq "$start" $((start + 40))); do
    if port_ok "$p"; then
      echo "$p"
      return 0
    fi
  done
  echo "No free host port near ${start} for ${name}" >&2
  exit 1
}

test -f .env || cp .env.example .env

http="$(pick "$LOCAL_HTTP_PORT" HTTP)"
https="$(pick "$LOCAL_HTTPS_PORT" HTTPS)"
pg="$(pick "$LOCAL_POSTGRES_PORT" Postgres)"

cat >"$COMPOSE_OVERRIDE" <<EOF
# Generated by make up-local — gitignored, do not commit.
services:
  postgres:
    ports:
      - "127.0.0.1:${pg}:5432"
  api-gateway:
    ports:
      - "${http}:80"
      - "${https}:443"
EOF

echo "Wrote ${COMPOSE_OVERRIDE}: HTTP=${http} HTTPS=${https} Postgres=127.0.0.1:${pg}"

$COMPOSE up -d --build --wait

echo ""
echo "Local stack is up (override ports, not committed):"
echo "  HTTPS  https://localhost:${https}"
echo "  HTTP   http://localhost:${http}"
echo "  DB     127.0.0.1:${pg}"
