#!/usr/bin/env bash
# Mobile SIP (port 5161) diagnostics — run on the affected PBX as root
echo "═══════════════════════════════════════════════════════"
echo "  Mobile SIP Transport Diagnostics"
echo "═══════════════════════════════════════════════════════"

HOST=$(grep '^APP_URL=' /var/www/html/.env | cut -d/ -f3)
echo ""
echo "PBX hostname: $HOST"

echo ""
echo "── 1. Is port 5161 listening? ──"
ss -tlnp 2>/dev/null | grep 5161 || echo "  ✗ NOT listening — transport-tls-mobile not loaded"

echo ""
echo "── 2. Is the transport loaded in Asterisk? ──"
asterisk -rx 'pjsip show transports' 2>/dev/null | grep -E "mobile|5161" || echo "  ✗ transport-tls-mobile NOT loaded"

echo ""
echo "── 3. Is port 5161 open in the firewall? ──"
nft list ruleset 2>/dev/null | grep -E "5161" | grep -i accept || echo "  ✗ 5161 NOT open in firewall"

echo ""
echo "── 4. Does the mobile transport config exist? ──"
if [ -f /etc/asterisk/pjsip_mobile.conf ]; then
    echo "  ✓ /etc/asterisk/pjsip_mobile.conf exists"
    grep -E "cert_file|bind|external_signaling_address" /etc/asterisk/pjsip_mobile.conf | sed 's/^/    /'
else
    echo "  ✗ /etc/asterisk/pjsip_mobile.conf MISSING"
fi

echo ""
echo "── 5. Can Asterisk read the cert? ──"
CERT=$(grep cert_file /etc/asterisk/pjsip_mobile.conf 2>/dev/null | cut -d= -f2)
if [ -n "$CERT" ]; then
    sudo -u asterisk test -r "$CERT" && echo "  ✓ asterisk can read $CERT" || echo "  ✗ asterisk CANNOT read $CERT"
fi

echo ""
echo "── 6. TLS handshake test (local) ──"
echo "Q" | timeout 5 openssl s_client -connect 127.0.0.1:5161 -servername "$HOST" 2>&1 | grep -E "subject=|Verify return|Cipher is" | sed 's/^/    /'

echo ""
echo "── 7. TLS handshake test (public hostname) ──"
echo "Q" | timeout 5 openssl s_client -connect "$HOST:5161" -servername "$HOST" 2>&1 | grep -E "subject=|Verify return|Cipher is|connect:" | sed 's/^/    /'

echo ""
echo "═══════════════════════════════════════════════════════"
echo "  If section 1, 2, 3 or 7 show ✗, that's the problem."
echo "  Fix: sudo php artisan pbx:setup-mobile-transport --reload"
echo "═══════════════════════════════════════════════════════"
