#!/bin/bash
set -euo pipefail

SOURCE="/opt/vpn-feed/nodes.txt"
OUTPUT="/opt/vpn-feed/sub.txt"
CLIENTS="/opt/vpn-panel/clients.json"
BACKUP_DIR="/opt/vpn-feed/backups"

REMOTE="root@104.252.19.38"
REMOTE_PORT="443"
SSH_KEY="/root/.ssh/vpnfeed_hostvds"
REMOTE_DIR="/var/www/vpn-feed/api/sub"

mkdir -p "$BACKUP_DIR"

if [ ! -s "$SOURCE" ]; then
    echo "ERROR: nodes.txt is empty or missing"
    exit 1
fi

if ! grep -q '^vless://' "$SOURCE"; then
    echo "ERROR: nodes.txt does not contain a VLESS profile"
    exit 1
fi

if [ ! -s "$CLIENTS" ]; then
    echo "ERROR: clients.json missing"
    exit 1
fi

if [ -s "$OUTPUT" ]; then
    cp "$OUTPUT" "$BACKUP_DIR/sub-$(date +%Y%m%d-%H%M%S).txt"
fi

base64 -w 0 "$SOURCE" > "$OUTPUT"
printf '\n' >> "$OUTPUT"

python3 - "$CLIENTS" "$OUTPUT" "$REMOTE" "$REMOTE_PORT" "$SSH_KEY" "$REMOTE_DIR" <<'PY'
import json
import subprocess
import sys
from pathlib import Path

clients_file, output, remote, remote_port, ssh_key, remote_dir = sys.argv[1:]

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

active_tokens = []

for c in clients:
    token = c.get("token")
    if not token:
        continue

    remote_file = f"{remote_dir}/{token}"

    if c.get("enabled", True):
        subprocess.run([
            "scp",
            "-i", ssh_key,
            "-P", remote_port,
            "-o", "BatchMode=yes",
            "-o", "ConnectTimeout=10",
            output,
            f"{remote}:{remote_file}"
        ], check=True)
        active_tokens.append(token)
    else:
        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"Published for {len(active_tokens)} active client(s)")
PY

find "$BACKUP_DIR" -type f -name 'sub-*.txt' -mtime +14 -delete

echo "Subscription published successfully."
