#!/bin/bash
set -e

WORK="/home/o11"
cd "$WORK"

IP="${SERVER_IP:-127.0.0.1}"
echo "[licserver] Using IP address: $IP"

# ── Patch server.js with the correct IP ─────────────────────────────────────
sed -i "s|const ipAddress = '';|const ipAddress = '${IP}';|" "$WORK/server.js"

# ── Generate self-signed TLS certs (if missing) ─────────────────────────────
if [ ! -f "$WORK/certs/key.pem" ] || [ ! -f "$WORK/certs/cert.pem" ]; then
    echo "[licserver] Generating self-signed TLS certificates..."
    openssl req -x509 -newkey rsa:2048 \
        -keyout "$WORK/certs/key.pem" \
        -out "$WORK/certs/cert.pem" \
        -days 365 -nodes \
        -subj "/CN=localhost" 2>/dev/null
    echo "[licserver] Certificates generated."
fi

# ── Start the license server (foreground — keeps container alive) ────────────
echo "[licserver] Starting license server on ports 80, 443, 5454..."
exec pm2-runtime start "$WORK/server.js" --name licserver
