#!/bin/bash
set -e

echo "[entrypoint] Generating .env for AGI scripts..."
cat > /var/www/pbx-app/.env << ENVEOF
DB_HOST=${DB_HOST}
DB_PORT=${DB_PORT}
DB_NAME=${DB_NAME}
DB_USER=${DB_USER}
DB_PASS=${DB_PASS}
APP_ENV=production
SESSION_NAME=pbx_session
SIGNALWIRE_SIP_DOMAIN=${SIGNALWIRE_SIP_DOMAIN}
ASTERISK_VOICEMAIL_SPOOL=/var/spool/asterisk/voicemail/default
ASTERISK_VOICEMAIL_CONF_PATH=/etc/asterisk-shared/voicemail_pbxapp.conf
ENVEOF
echo "[entrypoint] Wrote /var/www/pbx-app/.env"

echo "[entrypoint] Rendering Asterisk config from templates..."
for f in /etc/asterisk-templates/*; do
    name=$(basename "$f")
    # odbc.ini is a system-wide unixODBC file, not an Asterisk config —
    # handle it separately below rather than dropping it in /etc/asterisk/.
    if [[ "$name" == "odbc.ini.template" ]]; then
        continue
    fi
    if [[ "$name" == *.template ]]; then
        target="/etc/asterisk/${name%.template}"
        envsubst < "$f" > "$target"
        echo "[entrypoint] Rendered $target"
    else
        cp "$f" "/etc/asterisk/$name"
        echo "[entrypoint] Copied $name (static, no substitution)"
    fi
done

echo "[entrypoint] Setting up TLS certificate for SignalWire (TLS-only SIP delivery)..."
mkdir -p /var/lib/asterisk/keys
if [ ! -f /var/lib/asterisk/keys/asterisk.pem ]; then
    openssl req -new -x509 -days 3650 -nodes \
        -out /var/lib/asterisk/keys/asterisk.pem \
        -keyout /var/lib/asterisk/keys/asterisk.key \
        -subj "/CN=${PUBLIC_IP}" 2>&1 | grep -v "^\.\+$\|^+\+$" || true
    cat /var/lib/asterisk/keys/asterisk.key >> /var/lib/asterisk/keys/asterisk.pem
    echo "[entrypoint] Generated new self-signed TLS certificate"
else
    echo "[entrypoint] Reusing existing TLS certificate from persisted volume"
fi

echo "[entrypoint] Setting up ODBC driver registration..."
MARIADB_ODBC_DRIVER=$(find / -name "libmaodbc.so*" 2>/dev/null | head -1)
if [ -z "$MARIADB_ODBC_DRIVER" ]; then
    echo "[entrypoint] ERROR: MariaDB ODBC driver (libmaodbc.so) not found — is the odbc-mariadb package installed?"
    exit 1
fi
echo "[entrypoint] Found MariaDB ODBC driver at: $MARIADB_ODBC_DRIVER"

cat > /etc/odbcinst.ini << EOF
[MariaDB]
Description=MariaDB ODBC Driver
Driver=$MARIADB_ODBC_DRIVER
EOF

envsubst < /etc/asterisk-templates/odbc.ini.template > /etc/odbc.ini
echo "[entrypoint] Rendered /etc/odbc.ini and /etc/odbcinst.ini"

# The generated voicemail.conf #includes this shared file — it must exist
# before Asterisk starts, even if the app container hasn't created an
# extension yet (fresh deploy).
mkdir -p /etc/asterisk-shared
if [ ! -f /etc/asterisk-shared/voicemail_pbxapp.conf ]; then
    echo "[default]" > /etc/asterisk-shared/voicemail_pbxapp.conf
    echo "[entrypoint] Created empty voicemail_pbxapp.conf placeholder (no extensions yet)"
fi

chown -R asterisk:asterisk /etc/asterisk /var/lib/asterisk /var/log/asterisk /var/spool/asterisk

echo "[entrypoint] Starting voicemail-conf reload watcher in background..."
/usr/local/bin/voicemail-reload-watcher.sh &

echo "[entrypoint] Starting Asterisk..."
exec "$@"
