#!/usr/bin/env bash
set -e

# ==============================================================================
#  Rezerv VPN - Универсальный установщик для Linux (GUI + CLI)
# ==============================================================================

RED='\033[0;31m'
GREEN='\033[0;32m'
CYAN='\033[0;36m'
YELLOW='\033[1;33m'
NC='\033[0m'

echo -e "${CYAN}======================================================${NC}"
echo -e "${GREEN}       Установка Rezerv VPN для Linux (GUI + CLI)     ${NC}"
echo -e "${CYAN}======================================================${NC}"

# 1. Проверка прав root
if [ "$EUID" -ne 0 ]; then
    echo -e "${RED}[-] Пожалуйста, запустите скрипт с правами root (через sudo).${NC}"
    echo -e "    Пример: sudo bash install_linux.sh"
    exit 1
fi

INSTALL_DIR="/opt/rezerv-vpn"
BIN_DIR="/usr/local/bin"
DESKTOP_DIR="/usr/share/applications"
ICON_DIR_512="/usr/share/icons/hicolor/512x512/apps"
ICON_DIR_128="/usr/share/icons/hicolor/128x128/apps"
PIXMAPS_DIR="/usr/share/pixmaps"
DOWNLOAD_BASE="http://188.137.254.130/downloads"

mkdir -p "$INSTALL_DIR"
mkdir -p "$BIN_DIR"
mkdir -p "$DESKTOP_DIR"
mkdir -p "$ICON_DIR_512"
mkdir -p "$ICON_DIR_128"
mkdir -p "$PIXMAPS_DIR"
mkdir -p /etc/rezerv

# 2. Установка необходимых системных утилит и библиотек (GTK3, libcap, etc.)
echo -e "${CYAN}[*] Проверка и установка системных зависимостей...${NC}"
if command -v apt-get >/dev/null 2>&1; then
    apt-get update -qq && apt-get install -y -qq libcap2-bin curl tar iproute2 xdg-utils libgtk-3-0 liblzma5 libsecret-1-0 libjsoncpp25 >/dev/null 2>&1 || true
elif command -v dnf >/dev/null 2>&1; then
    dnf install -y -q libcap curl tar iproute xdg-utils gtk3 xz-libs >/dev/null 2>&1 || true
elif command -v pacman >/dev/null 2>&1; then
    pacman -Sy --noconfirm libcap curl tar iproute2 xdg-utils gtk3 xz >/dev/null 2>&1 || true
fi

# 3. Скачивание и распаковка дистрибутива
ARCH=$(uname -m)
if [ "$ARCH" != "x86_64" ] && [ "$ARCH" != "aarch64" ]; then
    echo -e "${RED}[-] Архитектура $ARCH не поддерживается напрямую.${NC}"
    exit 1
fi

echo -e "${CYAN}[*] Загрузка файлов Rezerv VPN...${NC}"
TMP_TAR="/tmp/rezerv-vpn-linux-${ARCH}.tar.gz"
curl -fSL "${DOWNLOAD_BASE}/rezerv-vpn-linux-${ARCH}.tar.gz" -o "$TMP_TAR" || \
curl -fSL "${DOWNLOAD_BASE}/rezerv-vpn-linux-x86_64.tar.gz" -o "$TMP_TAR" || \
curl -fSL "${DOWNLOAD_BASE}/rezerv-vpn-linux.tar.gz" -o "$TMP_TAR"

echo -e "${CYAN}[*] Распаковка в $INSTALL_DIR...${NC}"
tar -xzf "$TMP_TAR" -C "$INSTALL_DIR"
rm -f "$TMP_TAR"

# 4. Настройка сетевых привилегий движка и setuid runner
echo -e "${CYAN}[*] Настройка сетевых прав и системных прав (rezerv_runner)...${NC}"
if [ -f "$INSTALL_DIR/rezerv_client" ]; then
    chown root:root "$INSTALL_DIR/rezerv_client"
    chmod 755 "$INSTALL_DIR/rezerv_client"
    setcap cap_net_admin,cap_net_raw,cap_net_bind_service+ep "$INSTALL_DIR/rezerv_client" 2>/dev/null || true
fi

if [ -f "$INSTALL_DIR/rezerv_runner.c" ]; then
    gcc -O2 "$INSTALL_DIR/rezerv_runner.c" -o "$INSTALL_DIR/rezerv_runner" 2>/dev/null || true
fi

if [ -f "$INSTALL_DIR/rezerv_runner" ]; then
    chown root:root "$INSTALL_DIR/rezerv_runner"
    chmod 4755 "$INSTALL_DIR/rezerv_runner"
fi

# Очистка старых временных конфигураций
rm -f /tmp/rezerv_vpn* 2>/dev/null || true

# 5. Установка CLI утилиты
if [ -f "$INSTALL_DIR/rezerv-cli" ]; then
    chmod +x "$INSTALL_DIR/rezerv-cli"
    ln -sf "$INSTALL_DIR/rezerv-cli" "$BIN_DIR/rezerv"
fi

# 6. Установка GUI приложения (Flutter Desktop)
if [ -f "$INSTALL_DIR/rezerv-vpn" ]; then
    chmod +x "$INSTALL_DIR/rezerv-vpn"
    cat << 'EOF' > "$INSTALL_DIR/rezerv-gui"
#!/bin/bash
DIR="/opt/rezerv-vpn"
cd "$DIR" || true
export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:$PATH"
export GDK_BACKEND="x11,wayland,*"
export FLUTTER_ENGINE_SWITCHES="--no-enable-impeller"

ARGS=()
for arg in "$@"; do
    if [ -n "$arg" ] && [ "$arg" != "%u" ] && [ "$arg" != "%U" ]; then
        ARGS+=("$arg")
    fi
done

exec "$DIR/rezerv-vpn" --no-enable-impeller "${ARGS[@]}"
EOF
    chmod +x "$INSTALL_DIR/rezerv-gui"
    ln -sf "$INSTALL_DIR/rezerv-gui" "$BIN_DIR/rezerv-gui"
fi

# 7. Установка иконки и .desktop ярлыка для меню приложений
mkdir -p /usr/share/icons/hicolor/512x512/apps \
         /usr/share/icons/hicolor/256x256/apps \
         /usr/share/icons/hicolor/128x128/apps \
         /usr/share/icons/hicolor/64x64/apps \
         /usr/share/icons/hicolor/48x48/apps \
         /usr/share/icons/hicolor/32x32/apps \
         /usr/share/pixmaps

if [ -f "$INSTALL_DIR/rezerv-vpn.png" ]; then
    for size in 512x512 256x256 128x128 64x64 48x48 32x32; do
        cp -f "$INSTALL_DIR/rezerv-vpn.png" "/usr/share/icons/hicolor/$size/apps/rezerv-vpn.png" 2>/dev/null || true
        cp -f "$INSTALL_DIR/rezerv-vpn.png" "/usr/share/icons/hicolor/$size/apps/site.rezerv.vpn.png" 2>/dev/null || true
    done
    cp -f "$INSTALL_DIR/rezerv-vpn.png" "$PIXMAPS_DIR/rezerv-vpn.png" 2>/dev/null || true
    cp -f "$INSTALL_DIR/rezerv-vpn.png" "$PIXMAPS_DIR/site.rezerv.vpn.png" 2>/dev/null || true
    gtk-update-icon-cache -f -t /usr/share/icons/hicolor 2>/dev/null || true
    update-icon-caches /usr/share/icons/* 2>/dev/null || true
fi

if [ -f "$INSTALL_DIR/rezerv-vpn.desktop" ]; then
    cp -f "$INSTALL_DIR/rezerv-vpn.desktop" "$DESKTOP_DIR/rezerv-vpn.desktop"
    cp -f "$INSTALL_DIR/rezerv-vpn.desktop" "$DESKTOP_DIR/site.rezerv.vpn.desktop"
    chmod 644 "$DESKTOP_DIR/rezerv-vpn.desktop" "$DESKTOP_DIR/site.rezerv.vpn.desktop"
    update-desktop-database "$DESKTOP_DIR" 2>/dev/null || true
fi

# 8. Регистрация URL протоколов rezerv:// и tt://
xdg-mime default rezerv-vpn.desktop x-scheme-handler/rezerv 2>/dev/null || true
xdg-mime default rezerv-vpn.desktop x-scheme-handler/tt 2>/dev/null || true

echo -e "${GREEN}======================================================${NC}"
echo -e "${GREEN}  ✅ Rezerv VPN успешно установлен на вашем компьютере! ${NC}"
echo -e "${GREEN}======================================================${NC}"
echo -e "🖥️  ${YELLOW}Графический клиент (GUI):${NC} Найдите ${CYAN}'Rezerv VPN'${NC} в меню приложений или выполните ${CYAN}rezerv-gui${NC}"
echo -e "💻  ${YELLOW}Консольный клиент (CLI):${NC}  Используйте команду ${CYAN}rezerv${NC}:\n"
echo -e "  • ${YELLOW}Подключение:${NC}    ${CYAN}rezerv connect \"rezerv://c/...\"${NC}"
echo -e "  • ${YELLOW}Список стран:${NC}   ${CYAN}rezerv servers${NC}"
echo -e "  • ${YELLOW}Смена локации:${NC}  ${CYAN}rezerv switch <de|us|nl|ru>${NC}"
echo -e "  • ${YELLOW}Статус и IP:${NC}    ${CYAN}rezerv status${NC}"
echo -e "  • ${YELLOW}Журнал логов:${NC}   ${CYAN}rezerv logs -f${NC}"
echo -e "  • ${YELLOW}Отключение:${NC}     ${CYAN}rezerv disconnect${NC}\n"
