"""Confirm CF origin-pull IP range unreachable from pfSense WAN."""
import paramiko, socket
socket.setdefaulttimeout(60)

HOST, PORT, USER = "172.16.0.1", 2248, "admin"
import subprocess as _sp, yaml as _y
PWD = _y.safe_load(_sp.run(["sops","-d","D:/vault/infrastructure/pfsense-firewall.sops.yaml"],capture_output=True,text=True,timeout=30,check=True).stdout)["credentials"]["password"]

CMDS = [
    ('traceroute to 162.158.0.1 (CF origin-pull range)',
     'traceroute -n -w 3 -m 12 162.158.0.1 2>&1 | head -20'),
    ('traceroute to 104.26.8.237 (CF client-facing, known working)',
     'traceroute -n -w 3 -m 12 104.26.8.237 2>&1 | head -20'),
    ('traceroute to 172.67.72.147 (CF edge, working)',
     'traceroute -n -w 3 -m 12 172.67.72.147 2>&1 | head -20'),
    ('More CF origin-pull IPs via nc',
     'for ip in 162.158.0.1 162.158.100.1 162.158.200.1 162.159.0.1 162.159.100.1 108.162.192.1 108.162.250.1; do printf "%-16s " "$ip"; nc -z -v -w 3 $ip 443 2>&1 | head -1; done'),
    ('Route table: do we have a specific route for 162.158?',
     'netstat -rn -f inet | grep -E "^162\\.|^default" | head -10'),
    ('BGP / gateway status',
     'pfSsh.php playback gatewaystatus 2>&1 | head -20 || echo "(no playback)"; cat /tmp/gw_status 2>/dev/null | head -20'),
]

def main():
    c = paramiko.SSHClient()
    c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    c.connect(HOST, port=PORT, username=USER, password=PWD,
              timeout=30, banner_timeout=30, look_for_keys=False, allow_agent=False)
    try:
        for label, cmd in CMDS:
            print(f'\n===== {label} =====', flush=True)
            stdin, stdout, stderr = c.exec_command(cmd, timeout=90)
            out = stdout.read().decode('utf-8','replace')
            err = stderr.read().decode('utf-8','replace')
            if out.strip(): print(out.rstrip())
            if err.strip() and 'stty' not in err:
                print(f'  [stderr] {err.rstrip()[:300]}')
    finally:
        c.close()

if __name__ == '__main__':
    main()
