#!/bin/bash
# ============================================================
# All-in-one entrypoint for BT-AI-Phone
# Runs Asterisk (PBX) AND the Node bridge/dashboard in ONE container.
# The program banner is printed by the bridge itself (index.js).
# ============================================================
set -e

# Runtime dirs
mkdir -p /var/run/asterisk /var/log/asterisk /var/spool/asterisk /etc/asterisk/managed /var/spool/asterisk/recording
chown -R asterisk:asterisk /var/run/asterisk /var/log/asterisk /var/spool/asterisk /etc/asterisk/managed 2>/dev/null || true

# ---- TLS certificate: stored ENCRYPTED at rest (baked-key AES, .enc files in
# ---- the vault); decrypted ONLY into RAM (/dev/shm) for Asterisk to use, so
# ---- the plaintext PEM never sits on disk anywhere. ------------------------
KEYS_RW="${CONFIG_DIR:-/host-config}/keys"     # writable vault keys dir
LIVE_TLS=/dev/shm/aiphone-tls                  # RAM-only runtime location
mkdir -p "$LIVE_TLS" && chmod 700 "$LIVE_TLS"
mkdir -p "$KEYS_RW" 2>/dev/null || true
# One-time migration: an older install (or the owner's own box) may still hold
# a PLAINTEXT cert — encrypt it, then delete the plaintext so it stops sitting
# on disk. Only runs when a plaintext pem exists and no .enc is present yet.
if [ -f "$KEYS_RW/asterisk.pem" ] && [ ! -f "$KEYS_RW/asterisk.pem.enc" ]; then
    if node /app/certdec.js encrypt "$KEYS_RW/asterisk.pem" "$KEYS_RW/asterisk.pem.enc" 2>/dev/null \
       && node /app/certdec.js encrypt "$KEYS_RW/asterisk.key" "$KEYS_RW/asterisk.key.enc" 2>/dev/null; then
        rm -f "$KEYS_RW/asterisk.pem" "$KEYS_RW/asterisk.key"
        echo "Migrated existing TLS certificate to encrypted storage."
    fi
fi
# Decrypt the encrypted cert into RAM for Asterisk (if one is installed).
if [ -f "$KEYS_RW/asterisk.pem.enc" ]; then
    if node /app/certdec.js decrypt "$KEYS_RW/asterisk.pem.enc" "$LIVE_TLS/asterisk.pem" 2>/dev/null \
       && node /app/certdec.js decrypt "$KEYS_RW/asterisk.key.enc" "$LIVE_TLS/asterisk.key" 2>/dev/null; then
        chmod 600 "$LIVE_TLS"/asterisk.pem "$LIVE_TLS"/asterisk.key 2>/dev/null || true
        echo "TLS certificate ready (decrypted in memory only)."
    else
        echo "WARNING: TLS certificate could not be decrypted — starting without TLS."
        rm -f "$LIVE_TLS"/asterisk.pem "$LIVE_TLS"/asterisk.key 2>/dev/null || true
    fi
fi

# Stock sample configs we never use — only produce boot warnings (must be
# removed at RUNTIME: /etc/asterisk is a docker VOLUME, build-time rm is discarded)
rm -f /etc/asterisk/extensions.ael /etc/asterisk/users.conf /etc/asterisk/extensions.lua

# Seed managed extensions file
[ -f /etc/asterisk/managed/extensions-sip.conf ] || echo "; Managed extensions" > /etc/asterisk/managed/extensions-sip.conf

# Build pjsip.conf = base (mounted) + managed, fixing cert paths
manage-extensions rebuild >/dev/null 2>&1 || cat /etc/asterisk/pjsip.base.conf > /etc/asterisk/pjsip.conf
echo "pjsip.conf built ($(grep -c '^; --- Extension' /etc/asterisk/managed/extensions-sip.conf 2>/dev/null || echo 0) managed extensions)"

# Start Asterisk in the background
echo "Starting Asterisk..."
asterisk -f &
ASTERISK_PID=$!

# Wait until Asterisk's ARI HTTP port answers before starting the bridge —
# otherwise the bridge's first ARI connect races Asterisk's boot and logs a
# harmless-but-alarming "ECONNREFUSED 127.0.0.1:8088" on every start.
for _ in $(seq 1 60); do
    (exec 3<>/dev/tcp/127.0.0.1/8088) 2>/dev/null && { exec 3>&- 3<&-; break; }
    sleep 0.5
done

# Public-IP auto-sync watcher (zero-touch repair when a dynamic IP changes;
# no-op on static-IP boxes; disable with <config>/ip-autosync-off)
/app/ip-sync &

# Start the Node bridge/dashboard in the foreground (PID lives = container lives)
echo "Starting bridge/dashboard..."
node loader.js &
NODE_PID=$!

# If either process exits, stop the container so Docker can restart it
wait -n "$ASTERISK_PID" "$NODE_PID"
echo "A core process exited — shutting down container."
kill "$ASTERISK_PID" "$NODE_PID" 2>/dev/null || true
exit 1
