#!/usr/bin/env bash
# Start the three Bangla QR systems as separate background processes (Ctrl-C stops all).
# Needs local PostgreSQL running and the one-time setup done (docs/RUNNING.md).
#   acquirer 34100 (umbrella app) · switch_sim 34200 (standalone project) · issuer 34300 (umbrella app)
#
# LAN=1 ./scripts/dev.sh   lets the issuer (34300) and acquirer (34100) listen on the network; the switch stays
#                          on loopback. Exposes the issuer's login-less web screens; its mobile API needs a key.
set -euo pipefail
root="$(cd "$(dirname "$0")/.." && pwd)"

# Load POSTGRES_PASSWORD etc. from .env (the Mix configs read them via System.get_env).
if [ -f "$root/.env" ]; then set -a; . "$root/.env"; set +a; fi

pids=()
trap 'kill "${pids[@]}" 2>/dev/null || true' EXIT INT TERM

for dir in bqr_switch_sim apps/bqr_acquirer apps/bqr_issuer; do
  if [ "$dir" = "apps/bqr_issuer" ] && [ "${LAN:-}" = "1" ]; then
    (cd "$root/$dir" && ISSUER_BIND_ALL=1 exec mix phx.server) &
  elif [ "$dir" = "apps/bqr_acquirer" ] && [ "${LAN:-}" = "1" ]; then
    (cd "$root/$dir" && ACQUIRER_BIND_ALL=1 exec mix phx.server) &
  else
    (cd "$root/$dir" && exec mix phx.server) &
  fi
  pids+=($!)
done
wait
