#!/bin/bash
set -euo pipefail

CLIENTS="/opt/vpn-panel/clients.json"
PROFILES="/opt/vpn-panel/profiles.json"

REMOTE="root@100.109.109.26"
REMOTE_PORT="22"
SSH_KEY="/root/.ssh/vpncontrol_vps"
REMOTE_DIR="/var/www/vpn-feed/api/sub"

BACKUP_DIR="/opt/vpn-feed/backups"
LOCAL_DIR="/opt/vpn-feed/api/sub"

mkdir -p "$BACKUP_DIR"
mkdir -p "$LOCAL_DIR"

python3 - "$CLIENTS" "$PROFILES" "$REMOTE" "$REMOTE_PORT" "$SSH_KEY" "$REMOTE_DIR" "$BACKUP_DIR" "$LOCAL_DIR" <<'PY'
import base64
import json
import shutil
import subprocess
import sys
from datetime import datetime
from pathlib import Path
from urllib.parse import quote

clients_file, profiles_file, remote, remote_port, ssh_key, remote_dir, backup_dir, local_dir = sys.argv[1:]

clients = json.loads(Path(clients_file).read_text())
profiles = json.loads(Path(profiles_file).read_text())

vless_profiles = [
    p for p in profiles
    if p.get("type") == "vless" and p.get("publish")
]

if not vless_profiles:
    raise RuntimeError("Нет VLESS профилей с publish=true")

def build_vless(p, client_uuid):
    q = [
        "encryption=none",
        "security=reality",
        f"sni={quote(p['sni'], safe='')}",
        f"fp={quote(p['fp'], safe='')}",
        f"pbk={quote(p['pbk'], safe='-_')}",
        f"sid={quote(p['sid'], safe='')}",
        f"type={quote(p['transport'], safe='')}",
    ]

    if p.get("transport") == "xhttp":
        q.append(
            f"path={quote(p.get('path', ''), safe='')}"
        )
        q.append(
            f"mode={quote(p.get('mode', 'auto'), safe='')}"
        )

    if p.get("transport") in ("tcp", "raw") and p.get("flow"):
        q.append(
            f"flow={quote(p['flow'], safe='')}"
        )

    return (
        f"vless://{client_uuid}@{p['host']}:{p['port']}?"
        + "&".join(q)
        + "#"
        + quote(p["name"], safe="-_")
    )

published = 0

for c in clients:
    token = c.get("token")
    client_uuid = c.get("vless_uuid")
    enabled = c.get("enabled", True)

    if not token:
        print(f"SKIP {c['name']}: no token")
        continue

    remote_file = f"{remote_dir}/{token}"
    local_file = Path(local_dir) / token

    if not enabled:
        local_file.unlink(missing_ok=True)

        subprocess.run([
            "ssh",
            "-i", ssh_key,
            "-p", remote_port,
            "-o", "BatchMode=yes",
            "-o", "ConnectTimeout=10",
            remote,
            f"rm -f '{remote_file}'"
        ], check=True)

        print(f"DISABLED {c['name']}")
        continue

    if not client_uuid:
        print(f"SKIP {c['name']}: no vless_uuid")
        continue

    links = [
        build_vless(p, client_uuid)
        for p in vless_profiles
    ]

    plain = "\n".join(links) + "\n"
    encoded = base64.b64encode(plain.encode()).decode() + "\n"

    temp = Path(f"/tmp/vpn-sub-{c['id']}.txt")
    temp.write_text(encoded)

    backup_path = Path(backup_dir) / (
        f"{c['name']}-{datetime.now().strftime('%Y%m%d-%H%M%S')}.txt"
    )
    shutil.copy2(temp, backup_path)

    # Публикуем ту же подписку локально на CT104.
    local_tmp = Path(local_dir) / f".{token}.tmp"
    shutil.copy2(temp, local_tmp)
    local_tmp.replace(local_file)

    subprocess.run([
        "scp",
        "-i", ssh_key,
        "-P", remote_port,
        "-o", "BatchMode=yes",
        "-o", "ConnectTimeout=10",
        str(temp),
        f"{remote}:{remote_file}"
    ], check=True)

    temp.unlink(missing_ok=True)

    print(f"PUBLISHED {c['name']} -> {client_uuid}")
    published += 1

for f in Path(backup_dir).glob("*.txt"):
    try:
        age = datetime.now().timestamp() - f.stat().st_mtime
        if age > 14 * 86400:
            f.unlink()
    except Exception:
        pass

print(f"Published for {published} active client(s)")
PY

echo "Subscription published successfully."
