#!/usr/bin/env python3
"""Fetch secrets from NAS, push to Nexus vault on DO droplet."""
import json, subprocess, sys, os

VAULT_URL = "http://127.0.0.1:3450"
TOKEN = sys.argv[1]

def ssh_nas(cmd):
    r = subprocess.run(
        ["ssh", "-o", "ConnectTimeout=5", "-o", "BatchMode=yes",
         "-i", os.path.expanduser("~/.ssh/nas-access"),
         "admin@100.121.134.33", cmd],
        capture_output=True, text=True)
    if r.returncode != 0:
        print(f"NAS error: {r.stderr}", file=sys.stderr)
        return None
    return r.stdout.rstrip('\n')

def push_secret(key):
    val = ssh_nas(key)
    if not val:
        return False
    payload = json.dumps({"value": val})
    r = subprocess.run(
        ["ssh", "-o", "ConnectTimeout=15", "-o", "BatchMode=yes",
         "-i", os.path.expanduser("~/.ssh/id_ghqgateway"),
         "salus-ops@100.67.103.48",
         f"curl -s -X PUT '{VAULT_URL}/secrets/{key}' "
         f"-H 'Authorization: Bearer {TOKEN}' "
         f"-H 'Content-Type: application/json' "
         f"-d {shlex_quote(payload)}"],
        capture_output=True, text=True)
    return r.stdout

def shlex_quote(s):
    return "'" + s.replace("'", "'\\''") + "'"

import shlex

secrets = {
    "b60_ssh_key": "cat /volume1/homes/admin/b60-ssh-key.pem",
    "b60_ssh_pub": "cat /volume1/homes/admin/b60-ssh-key.pub",
    "godaddy_api": "cat /volume1/backups/infrastructure/godaddy-credentials.txt",
    "do_ssh": "cat /volume1/backups/infrastructure/do-ssh-credentials.txt",
    "hetzner_ssh": "cat /volume1/backups/infrastructure/hetzner-ssh-credentials.txt",
}

for name, cmd in secrets.items():
    print(f"Pushing {name}...", end=" ", flush=True)
    val = ssh_nas(cmd)
    if val is None:
        print("FAIL (NAS unreachable)")
        continue
    payload = json.dumps({"value": val})
    quoted = shlex_quote(payload)
    r = subprocess.run(
        ["ssh", "-o", "ConnectTimeout=15", "-o", "BatchMode=yes",
         "-i", os.path.expanduser("~/.ssh/id_ghqgateway"),
         "salus-ops@100.67.103.48",
         f"curl -s -X PUT '{VAULT_URL}/secrets/{name}' "
         f"-H 'Authorization: Bearer {TOKEN}' "
         f"-H 'Content-Type: application/json' "
         f"-d {quoted}"],
        capture_output=True, text=True)
    if r.returncode != 0:
        print(f"FAIL ({r.stderr.strip()})")
    elif '"secret"' in r.stdout:
        print(f"OK - {json.loads(r.stdout)['secret']['key']} v{json.loads(r.stdout)['secret']['version']}")
    else:
        print(f"RESP: {r.stdout.strip()[:80]}")
