#!/bin/bash

# Проверка root
if [[ $EUID -ne 0 ]]; then
  echo "Запусти скрипт от root"
  exit 1
fi

echo "=== Установка зависимостей ==="
apt update && apt install -y curl uuid-runtime jq openssl lsof wget unzip ca-certificates

echo "=== Установка Xray ==="
bash -c "$(curl -L https://github.com/XTLS/Xray-install/raw/main/install-release.sh)" @ install

XRAY_BIN="/usr/local/bin/xray"
chmod +x $XRAY_BIN

echo "=== Генерация ключей ==="

UUID=$($XRAY_BIN uuid)
RAW_KEYS=$($XRAY_BIN x25519)

# Надёжный парсинг под новые версии Xray
PRIV_KEY=$(echo "$RAW_KEYS" | grep PrivateKey | awk -F ': ' '{print $2}')
PUB_KEY=$(echo "$RAW_KEYS" | grep PublicKey | awk -F ': ' '{print $2}')

SHORT_ID=$(openssl rand -hex 8)
SERVER_IP=$(curl -s https://api.ipify.org)

# Проверка
if [[ -z "$PRIV_KEY" || -z "$PUB_KEY" ]]; then
  echo "❌ Ошибка генерации ключей:"
  echo "$RAW_KEYS"
  exit 1
fi

echo "=== Создание конфигурации ==="

mkdir -p /usr/local/etc/xray/

cat <<EOF > /usr/local/etc/xray/config.json
{
  "log": {
    "loglevel": "warning"
  },
  "inbounds": [
    {
      "port": 443,
      "protocol": "vless",
      "settings": {
        "clients": [
          {
            "id": "$UUID",
            "flow": "xtls-rprx-vision"
          }
        ],
        "decryption": "none"
      },
      "streamSettings": {
        "network": "tcp",
        "security": "reality",
        "realitySettings": {
          "show": false,
          "dest": "www.cloudflare.com:443",
          "xver": 0,
          "serverNames": [
            "www.cloudflare.com"
          ],
          "privateKey": "$PRIV_KEY",
          "shortIds": [
            "$SHORT_ID"
          ]
        }
      }
    }
  ],
  "outbounds": [
    {
      "protocol": "freedom",
      "tag": "direct"
    }
  ]
}
EOF

echo "=== Запуск Xray ==="

systemctl daemon-reload
systemctl enable xray
systemctl restart xray

echo "=== Проверка ==="

if systemctl is-active --quiet xray; then
  echo ""
  echo "✅ ГОТОВО"
  echo ""
  echo "Ссылка для клиента:"
  echo ""
  echo "vless://$UUID@$SERVER_IP:443?security=reality&encryption=none&pbk=$PUB_KEY&headerType=none&sid=$SHORT_ID&type=tcp&flow=xtls-rprx-vision&sni=www.cloudflare.com#Timea Bella"
  echo ""
  echo "Проверка статуса:"
  echo "systemctl status xray"
else
  echo "❌ Xray не запустился"
  echo "Проверь порт:"
  echo "lsof -i :443"
fi
