#!/usr/bin/env bash
# arm-e-fetch.sh <ARM> <PORT> <EXE_PATH>
# Census (by port AND by program path) in the SAME command before and after, LAN fetch x3 from kitsubito, loopback control.
ARM=$1; PORT=$2; EXE=$3
census() {
  powershell -NoProfile -Command "
    \$rules = Get-NetFirewallRule -PolicyStore ActiveStore -Enabled True -Direction Inbound -Action Allow
    \$reach = \$rules | Where-Object {
      \$pf = \$_ | Get-NetFirewallPortFilter; \$af = \$_ | Get-NetFirewallApplicationFilter
      \$portok = (\$pf.Protocol -eq 'TCP' -or \$pf.Protocol -eq 'Any') -and (\$pf.LocalPort -eq 'Any' -or ((\$pf.LocalPort -join ',') -split ',') -contains '$PORT')
      \$exeok  = \$af.Program -eq 'Any' -or \$af.Program -ieq '$EXE'
      \$portok -and \$exeok }
    'census reach(port $PORT AND exe): ' + ((\$reach | ForEach-Object { \$adf=\$_|Get-NetFirewallAddressFilter; \$pf=\$_|Get-NetFirewallPortFilter; \$af=\$_|Get-NetFirewallApplicationFilter; '{0}[{1} {2} prof={3} local={6} remote={4} prog={5}]' -f \$_.DisplayName,\$pf.Protocol,\$pf.LocalPort,\$_.Profile,\$adf.RemoteAddress,\$af.Program,\$adf.LocalAddress } | Sort-Object -Unique) -join ' | ')
    'spt-w2a: ' + ((\$rules | Where-Object DisplayName -like 'spt-w2a*' | ForEach-Object DisplayName) -join ',')
  "
}
echo "=== ARM $ARM PORT $PORT EXE $EXE  $(date -u +%FT%TZ)"
echo "--- census BEFORE"; census
echo "--- listener"; powershell -NoProfile -Command "Get-NetTCPConnection -State Listen | ? LocalPort -eq $PORT | % { '{0}:{1} pid={2} exe={3}' -f \$_.LocalAddress,\$_.LocalPort,\$_.OwningProcess,(Get-Process -Id \$_.OwningProcess).Path }"
for i in 1 2 3; do curl -s -o /dev/null --connect-timeout 5 --max-time 8 -w "loopback control $i: http=%{http_code} total=%{time_total} " "http://127.0.0.1:$PORT/"; echo "curl_exit=$?"; done
ssh -o BatchMode=yes -o ConnectTimeout=10 reavus@kitsubito "date -u +%FT%TZ; for i in 1 2 3; do curl -s -o /dev/null --connect-timeout 6 --max-time 8 -w \"arm $ARM try \$i: http=%{http_code} connect=%{time_connect} total=%{time_total} \" http://192.168.1.81:$PORT/; echo curl_exit=\$?; done; date -u +%FT%TZ"
echo "--- census AFTER $(date -u +%FT%TZ)"; census
