#!/usr/bin/env bash
# =============================================================================
#  B2G platform - one-shot setup for Linux/macOS (and Git Bash on Windows)
#  Installs frontend dependencies, builds the Angular apps, builds the shared
#  backend image and deploys the full 14-container stack behind Kong (:8000).
#  Safe to re-run: npm install is skipped when node_modules already exists,
#  Docker layers are cached, and `docker compose up -d` is idempotent.
# =============================================================================
set -euo pipefail
cd "$(dirname "$0")"

FRONTENDS_INSTALL=(b2g gMarket b2g_website b2g_filems_fe nibe_datamanager/nibedatamanager_fe)
FRONTENDS_BUILD=(b2g_website gMarket b2g b2g_filems_fe nibe_datamanager/nibedatamanager_fe)   # lightest first

echo
echo "=== [1/5] Checking prerequisites ==="
command -v docker >/dev/null || { echo "ERROR: docker CLI not found."; exit 1; }
docker info >/dev/null 2>&1  || { echo "ERROR: Docker daemon is not running."; exit 1; }
command -v node >/dev/null   || { echo "ERROR: Node.js not found. Install Node 20 or 22."; exit 1; }
NODE_MAJOR=$(node -v | sed 's/^v\([0-9]*\).*/\1/')
[ "$NODE_MAJOR" -ge 20 ] || { echo "ERROR: Node 20+ required, found $(node -v)"; exit 1; }
echo "  docker: OK    node: $(node -v)"

echo
echo "=== [2/5] Building shared backend image b2g/php-nginx:8.2 ==="
docker build -t b2g/php-nginx:8.2 docker/php-nginx

# nibe_datamanager gitignores vendor/ (the other backends commit it) — needs a
# one-time composer install with PHP 8.2 so the bind-mounted container can boot.
if [ ! -d "nibe_datamanager/vendor" ]; then
    if command -v composer >/dev/null; then
        echo "  installing nibe_datamanager composer deps (PHP 8.2 required) ..."
        (cd nibe_datamanager && composer install --no-interaction)
    else
        echo "  WARNING: nibe_datamanager/vendor missing and composer not found -"
        echo "           run 'composer install' in nibe_datamanager/ with PHP 8.2 manually."
    fi
fi

echo
echo "=== [2b/5] Backend composer deps (only subpayment/zohoapi lack committed vendor/) ==="
for pack in b2g_subpayment b2g_zohoapi; do
    if [ -d "$pack" ] && [ ! -d "$pack/vendor" ]; then
        echo "  composer install: $pack ..."
        MSYS_NO_PATHCONV=1 docker run --rm -v "$(pwd)/$pack:/app" -w /app composer:2 \
            install --no-dev --no-interaction --ignore-platform-reqs
    fi
done

echo
echo "=== [3/5] Installing frontend dependencies (skipped when node_modules exists) ==="
for app in "${FRONTENDS_INSTALL[@]}"; do
    if [ ! -d "$app/node_modules" ]; then
        echo "  installing $app ..."
        (cd "$app" && npm install --legacy-peer-deps)
    else
        echo "  $app: node_modules present, skipping"
    fi
done

echo
echo "=== [4/5] Building Angular frontends (sequential - keeps RAM in check) ==="
for app in "${FRONTENDS_BUILD[@]}"; do
    if [ "$app" = "b2g_filems_fe" ]; then
        # Angular Elements micro-frontend: the portal SPAs load app/micro-fe.js +
        # app/styles.css from it (docker/fe-env/env.docker.js), so it needs unhashed
        # output plus the concat step - same recipe as its "bundle" npm script.
        echo "  building $app (micro-fe.js bundle) ..."
        (cd "$app" && npx ng build --configuration=docker --output-hashing=none --delete-output-path=false && node concat.js)
    else
        echo "  building $app ..."
        (cd "$app" && npx ng build --configuration=docker)
    fi
done

echo
echo "=== [5/5] Deploying the stack ==="
docker compose up -d
echo "  waiting for containers to settle..."
sleep 10
docker compose ps

echo
echo "=== Smoke test via Kong (http://localhost:8000) ==="
ROUTES=(micro/web usermg/web api profilemg/web configmg/web digitall/web \
        filemst/api cengex/web gmarketapi/web mail/web datamg/web \
        app market filems datamanager "")
for r in "${ROUTES[@]}"; do
    code=$(curl -s -o /dev/null -w "%{http_code}" --max-time 20 "http://localhost:8000/$r/" || echo ERR)
    printf '   /%-15s -> %s\n' "$r" "$code"
done
echo
echo "  NOTE: /configmg/web and /mail/web return 500 on their bare root URL only"
echo "        (missing default view) - their real API routes work. See README.md."
echo
echo "============================================================"
echo " DONE. Open:"
echo "   Website : http://localhost:8000/"
echo "   B2G app : http://localhost:8000/app/"
echo "   gMarket : http://localhost:8000/market/"
echo "   Filems  : http://localhost:8000/filems/"
echo "   DataMgr : http://localhost:8000/datamanager/"
echo "============================================================"
