#!/bin/bash
# remote_node_setup.sh — run this on a NEW VPS to join it to Lyoo's proxy panel
# Usage: bash <(curl -s http://149.104.5.95:8094/remote_node_setup.sh) \
#   --panel URL --token TOKEN --name "NodeName"
#
# Example: 
#   bash <(curl -s http://sailor.venus.lyoo.gay:8094/remote_node_setup.sh) \
#     --panel http://149.104.5.95:3053 --token hX6hgszeGJ29lNfBQQHJ0o09w6jhjGDAJxC1EJPjUftNT2AI \
#     --name "Azure-MY"
set -euo pipefail

# ── Parse args ──────────────────────────────────────────────
PANEL=""
TOKEN=""
NAME=""
while [[ $# -gt 0 ]]; do
    case $1 in
        --panel) PANEL="$2"; shift 2 ;;
        --token) TOKEN="$2"; shift 2 ;;
        --name)  NAME="$2";  shift 2 ;;
        *) echo "Unknown: $1"; exit 1 ;;
    esac
done
if [[ -z "$PANEL" || -z "$TOKEN" || -z "$NAME" ]]; then
    echo "Usage: $0 --panel URL --token TOKEN --name NODENAME"
    exit 1
fi

echo "=== Setting up node: $NAME ==="
echo "  Panel: $PANEL"
echo ""

# ── 1. Install 3xui ─────────────────────────────────────────
if ! command -v x-ui &>/dev/null; then
    echo "--- Installing 3x-ui ---"
    bash <(curl -Ls https://raw.githubusercontent.com/mhsanaei/3x-ui/master/install.sh) > /dev/null 2>&1
    echo "  3x-ui installed"
fi

# Configure 3xui
x-ui stop 2>/dev/null || true
x-ui setting -username admin 2>/dev/null || true
x-ui setting -password admin 2>/dev/null || true
x-ui setting -remove_secret 2>/dev/null || true
x-ui setting -port 3053 2>/dev/null || true
x-ui start

# ── 2. Install dependencies ─────────────────────────────────
apt update -qq && apt install -y -qq python3 ufw curl sqlite3

# ── 3. Configure UFW ────────────────────────────────────────
ufw --force reset
ufw default deny incoming
ufw default allow outgoing
ufw allow 22/tcp
ufw allow 4443/tcp
ufw allow 8443/udp
ufw --force enable

# ── 4. Register in panel ────────────────────────────────────
echo "--- Registering node ---"
NEXT_ID=$(curl -s -k -H "Authorization: Bearer $TOKEN" \
  "$PANEL/panel/api/nodes/list" | python3 -c "
import sys,json
d=json.load(sys.stdin)
nodes=d.get('obj',[])
mx=max((n.get('id',0) for n in nodes), default=0)
print(mx+1)")

curl -s -k -X POST -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d "{\"name\":\"$NAME\",\"address\":\"$(curl -s ifconfig.me)\",\"port\":26703,\"enable\":true}" \
  "$PANEL/panel/api/nodes/add" > /dev/null
echo "  Registered as node ID: $NEXT_ID"

# ── 5. Create Reality inbound on panel ──────────────────────
REMOTE_IP=$(curl -s ifconfig.me)
echo "--- Creating inbounds on panel for $NAME ---"

# 5a: VLESS Reality (port 4443)
curl -s -k -X POST -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d "{
    \"up\":0,\"down\":0,\"total\":0,
    \"remark\":\"$NAME VLESS-Reality\",
    \"enable\":true,\"expiryTime\":0,
    \"listen\":\"0.0.0.0\",\"port\":4443,\"protocol\":\"vless\",
    \"settings\":{\"clients\":[],\"decryption\":\"none\"},
    \"streamSettings\":{
      \"network\":\"tcp\",\"security\":\"reality\",
      \"realitySettings\":{
        \"target\":\"dl.google.com:443\",
        \"serverNames\":[\"dl.google.com\"],
        \"privateKey\":\"gDjL4omHsTSFwAhZYrfdpvrQZkGueQrjU-3NfevIqns\",
        \"shortIds\":[\"6a34ac64fbe50e\",\"2ab9f61494\",\"b6a9601b\",\"e061dfb2fbba\"]
      }
    },
    \"tag\":\"$NAME-vless-reality\",
    \"nodeId\":$NEXT_ID
  }" "$PANEL/panel/api/inbounds/add" > /dev/null
echo "  Reality inbound created on panel"

# 5b: Hysteria2 (port 8443)
curl -s -k -X POST -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d "{
    \"up\":0,\"down\":0,\"total\":0,
    \"remark\":\"$NAME Hysteria2\",
    \"enable\":true,\"expiryTime\":0,
    \"listen\":\"0.0.0.0\",\"port\":8443,\"protocol\":\"hysteria2\",
    \"settings\":{\"clients\":[],\"version\":2},
    \"streamSettings\":{
      \"network\":\"udp\",\"security\":\"tls\",
      \"tlsSettings\":{
        \"serverName\":\"sailor.moon.lyoo.gay\",
        \"certificates\":[{\"certificateFile\":\"/etc/x-ui/cert/jp-cert.pem\",\"keyFile\":\"/etc/x-ui/cert/jp-key.pem\"}]
      }
    },
    \"tag\":\"$NAME-hysteria2\",
    \"nodeId\":$NEXT_ID
  }" "$PANEL/panel/api/inbounds/add" > /dev/null
echo "  Hysteria2 inbound created on panel"

# ── 6. Restart xray on panel to push to node ────────────────
curl -s -k -X POST -H "Authorization: Bearer $TOKEN" \
  "$PANEL/panel/api/server/restartXrayService" > /dev/null
echo "  Panel xray restarted — config pushed to node"
sleep 8

# ── 7. Fix node Reality config (node sync strips clients) ───
echo "--- Fixing node config ---"
cat > /opt/fix_node_reality.py << 'PYEOF'
#!/usr/bin/env python3
"""Re-apply Reality/Hy2 clients after node sync overwrites them."""
import json
with open("/usr/local/x-ui/bin/config.json") as f:
    c = json.load(f)
changed = False
for ib in c.get("inbounds", []):
    p = ib.get("port")
    if p in (443, 4443) and not ib.get("settings", {}).get("clients"):
        ib["settings"]["clients"] = [{"email": "me@lyoo.gay", "flow": "xtls-rprx-vision", "id": "3c717802-e008-4807-9bac-68805ae88c68"}]
        ib["settings"]["testseed"] = [900, 500, 900, 256]
        rs = ib.get("streamSettings", {}).get("realitySettings", {})
        rs["target"] = "dl.google.com:443"
        rs["maxClientVer"] = ""; rs["maxTimediff"] = 0
        changed = True
    elif p == 8443 and not ib.get("settings", {}).get("clients"):
        ib["settings"]["clients"] = [{"email": "me@lyoo.gay", "auth": "5p9dm1cq67kru1w3", "id": "3c717802-e008-4807-9bac-68805ae88c68"}]
        ib["settings"]["version"] = 2
        changed = True
if changed:
    with open("/usr/local/x-ui/bin/config.json", "w") as f:
        json.dump(c, f, indent=2)
    import subprocess
    subprocess.run(["systemctl", "restart", "x-ui"], capture_output=True)
    print("Fixed clients on node")
PYEOF
chmod +x /opt/fix_node_reality.py
python3 /opt/fix_node_reality.py
sleep 5

# ── 8. Verify ──────────────────────────────────────────────
echo ""
echo "=== Verification ==="
echo "  xray: $(pgrep -f xray-linux-amd64 | wc -l) process(es)"
echo "  Reality (4443): $(ss -tlnp 2>/dev/null | grep 4443 | head -1 || echo 'down')"
echo "  Hysteria2 (8443): $(ss -ulnp 2>/dev/null | grep 8443 | head -1 || echo 'down')"
echo ""

echo "=== Node $NAME setup complete ==="
echo "  Inbounds created: Reality (4443/tcp), Hysteria2 (8443/udp)"
echo "  Panel: $PANEL"
echo "  Next: run /opt/fix_node_reality.py after every panel xray restart"
echo ""
