#!/usr/bin/env python3
"""vpsbit-Server-Wache: prueft galaktikus-forge-1 (625) UND galaktikus-2/Titan (630).
Weg 1: Direktabruf vpsbit-API (neuer Host fn164/185.100.87.120, IP nicht geblockt).
Weg 2 (Fallback): EQVPS-Sprungserver via SSH (falls Direktabruf 403/Netzfehler).
Druckt NUR bei ZUSTANDSAENDERUNG (neuer Server / status=active)."""
import json, os, sys, subprocess, urllib.request, http.cookiejar

SSH = ["ssh", "-i", os.path.expanduser("~/.ssh/eqvps_pro64_ed25519"),
       "-o", "StrictHostKeyChecking=accept-new", "-o", "ConnectTimeout=20",
       "-o", "BatchMode=yes", "root@77.42.60.200"]
STATE_DIR = os.path.expanduser("~/.hermes/profiles/galaktikus/cache/scratch")

SERVERS = [
    # (Label, Token-Datei, SSH-Key-Hinweis)
    ("galaktikus-forge-1", "~/.secrets/vpsbit_forge_account.json",
     "SSH-Key ~/.ssh/gk_forge_ed25519 (Forge: 16c/32GB, Node-3/Farm)"),
    ("galaktikus-2", "~/.secrets/vpsbit_galaktikus2_account.json",
     "SSH-Key ~/.ssh/gk_galaktikus2_ed25519 (Titan 8 vCPU/32GB ECC: NEUER GALAKTIKUS-KOERPER, Klon-Umzug starten)"),
]

REMOTE = r'''
import json, urllib.request
tok = "TOKENLITERAL"
req = urllib.request.Request("https://vpsbit.io/api/login",
    data=json.dumps({"mode":"token","token":tok,"tos":True}).encode(),
    headers={"Content-Type":"application/json","Origin":"https://vpsbit.io",
             "Referer":"https://vpsbit.io/panel/","User-Agent":"Mozilla/5.0"})
r = urllib.request.urlopen(req, timeout=30)
cookie = r.headers.get("Set-Cookie","").split(";")[0]
req = urllib.request.Request("https://vpsbit.io/api/servers",
    headers={"Cookie":cookie,"Origin":"https://vpsbit.io","Referer":"https://vpsbit.io/panel/","User-Agent":"Mozilla/5.0"})
print(urllib.request.urlopen(req, timeout=30).read().decode())
'''

HDRS = {"Content-Type": "application/json", "Origin": "https://vpsbit.io",
        "Referer": "https://vpsbit.io/panel/", "User-Agent": "Mozilla/5.0"}

def query_direct(tok):
    cj = http.cookiejar.CookieJar()
    op = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
    req = urllib.request.Request("https://vpsbit.io/api/login",
        data=json.dumps({"mode": "token", "token": tok, "tos": True}).encode(), headers=HDRS)
    op.open(req, timeout=30).read()
    req = urllib.request.Request("https://vpsbit.io/api/servers", headers=HDRS)
    return json.loads(op.open(req, timeout=30).read().decode()).get("servers", [])

def query(tokenfile):
    tok = json.load(open(os.path.expanduser(tokenfile)))["account_token"]
    try:
        return query_direct(tok)
    except Exception as e:
        err = repr(e)[:150]
        if not os.path.exists(SSH[1]):
            raise RuntimeError(f"Direktabruf fehlgeschlagen ({err}) und EQVPS-Sprung-Key {SSH[1]} fehlt")
        script = REMOTE.replace("TOKENLITERAL", tok)
        r = subprocess.run(SSH + ["python3", "-"], input=script, capture_output=True, text=True, timeout=90)
        if r.returncode != 0:
            raise RuntimeError(f"Direktabruf ({err}) und EQVPS-Sprung fehlgeschlagen: {r.stderr.strip()[:150]}")
        return json.loads(r.stdout.strip().splitlines()[-1]).get("servers", [])

def main():
    any_output = False
    for label, tokenfile, hint in SERVERS:
        state_file = os.path.join(STATE_DIR, f"vpsbit_wache_{label}.txt")
        try:
            servers = query(tokenfile)
        except Exception as e:
            print(f"VPSBIT-WACHE FEHLER ({label}): {e}")
            any_output = True
            continue
        mine = [s for s in servers if s.get("label") == label]
        if not mine:
            print(f"{label}: Server nicht (mehr) im Account sichtbar")
            any_output = True
            continue
        s = mine[0]
        # IP: vpsbit liefert sie erst mit status=active im Server-Eintrag
        sig = json.dumps({k: s.get(k) for k in ("id","status","power_state","ip","ipv4","address")}, sort_keys=True)
        old = ""
        try:
            old = open(state_file).read().strip()
        except OSError:
            pass
        if sig != old:
            open(state_file, "w").write(sig)
            tag = label.upper()
            if s.get("status") == "active":
                ip = s.get("ip") or s.get("ipv4") or s.get("address") or "IP im Panel ablesen"
                print(f"{tag} AKTIV! Server-ID {s.get('id')} — IP: {ip}. {hint}")
            else:
                print(f"{tag}-Statuswechsel: {s.get('status')} (Server-ID {s.get('id')}) — noch kein GO fuer Setup.")
            any_output = True
    if not any_output:
        pass  # stille Post: nichts geaendert

if __name__ == "__main__":
    main()
