-- =====================================================================
-- Migration 060: Add AIVPN protocol (AI-powered VPN with traffic disguise)
-- https://github.com/infosave2007/aivpn
-- Neural Resonance AI for DPI bypass, Zero-RTT, PFS
-- =====================================================================

-- 1. Insert the AIVPN protocol
INSERT INTO protocols (name, slug, description, install_script, uninstall_script, output_template, show_text_content, ubuntu_compatible, is_active, definition, created_at, updated_at)
SELECT
  'AIVPN',
  'aivpn',
  'AIVPN — AI-powered VPN с маскировкой трафика под реальные приложения (Zoom, TikTok, DNS). Neural Resonance для обхода DPI.',
  '#!/bin/bash
set -euo pipefail

# Use exported variables from panel (SERVER_PORT, SERVER_CONTAINER) or defaults
CONTAINER_NAME="${SERVER_CONTAINER:-aivpn-server}"
VPN_PORT="${SERVER_PORT:-443}"
CONFIG_DIR="/etc/aivpn"

# Install git and iptables if not available
if ! command -v git &> /dev/null || ! command -v iptables &> /dev/null; then
  apt-get update -qq
  if ! command -v git &> /dev/null; then
    apt-get install -y -qq git >/dev/null 2>&1
  fi
  if ! command -v iptables &> /dev/null; then
    apt-get install -y -qq iptables >/dev/null 2>&1
  fi
fi

# Install Docker if not available
if ! command -v docker &> /dev/null; then
  apt-get update -qq
  apt-get install -y -qq apt-transport-https ca-certificates curl gnupg lsb-release >/dev/null 2>&1
  curl -fsSL https://download.docker.com/linux/ubuntu/gpg | gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg
  echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable" > /etc/apt/sources.list.d/docker.list
  apt-get update -qq && apt-get install -y -qq docker-ce docker-ce-cli containerd.io >/dev/null 2>&1
fi

mkdir -p "$CONFIG_DIR"

# Enable IP forwarding
sysctl -w net.ipv4.ip_forward=1 2>/dev/null || true

# Generate server key if not exists
if [ ! -f "$CONFIG_DIR/server.key" ]; then
  openssl rand 32 > "$CONFIG_DIR/server.key"
  chmod 600 "$CONFIG_DIR/server.key"
  echo "Generated new AIVPN server key"
else
  echo "Using existing AIVPN server key"
fi

# Setup NAT
iptables -t nat -C POSTROUTING -s 10.0.0.0/24 -o eth0 -j MASQUERADE 2>/dev/null || \
  iptables -t nat -A POSTROUTING -s 10.0.0.0/24 -o eth0 -j MASQUERADE

# Get external IP
EXTERNAL_IP=$(curl -s -4 ifconfig.me 2>/dev/null || curl -s -4 icanhazip.com 2>/dev/null || echo "YOUR_SERVER_IP")

# Clone AIVPN source for Docker build
if [ ! -d /opt/amnezia/aivpn ]; then
  git clone --depth=1 https://github.com/infosave2007/aivpn.git /opt/amnezia/aivpn
fi

# Build Docker image
cd /opt/amnezia/aivpn
docker build --no-cache -t aivpn-server -f Dockerfile .

# Remove existing container
docker rm -f "$CONTAINER_NAME" >/dev/null 2>&1 || true

# Run AIVPN container
docker run -d --name "$CONTAINER_NAME" --restart always --cap-add=NET_ADMIN --device /dev/net/tun --network host -v "$CONFIG_DIR:/etc/aivpn" aivpn-server --listen "0.0.0.0:${VPN_PORT}" --key-file /etc/aivpn/server.key

sleep 3

# Check container status
STATUS=$(docker inspect --format="{{.State.Status}}" "$CONTAINER_NAME" 2>/dev/null || echo "unknown")
if [ "$STATUS" != "running" ]; then
  echo "ERROR: AIVPN container is not running"
  docker logs "$CONTAINER_NAME" 2>&1
  exit 1
fi

echo "AIVPN installed successfully"
echo "Port: $VPN_PORT"
echo "ExternalIP: $EXTERNAL_IP"
echo "ConfigDir: $CONFIG_DIR"',
  '#!/bin/bash
set -euo pipefail

CONTAINER_NAME="${CONTAINER_NAME:-aivpn-server}"

docker stop "$CONTAINER_NAME" 2>/dev/null || true
docker rm -fv "$CONTAINER_NAME" 2>/dev/null || true
docker image rm aivpn-server 2>/dev/null || true
rm -rf /opt/amnezia/aivpn 2>/dev/null || true

# Remove NAT rules
iptables -t nat -D POSTROUTING -s 10.0.0.0/24 -o eth0 -j MASQUERADE 2>/dev/null || true

echo "{\"success\":true,\"message\":\"AIVPN uninstalled\"}"',
  'aivpn://{{connection_key}}',
  1,
  1,
  1,
  JSON_OBJECT(
    'engine', 'shell',
    'metadata', JSON_OBJECT(
      'container_name', 'aivpn-server',
      'port_range', JSON_ARRAY(443, 443),
      'config_dir', '/etc/aivpn',
      'vpn_subnet', '10.0.0.0/24',
      'requires_docker_build', true,
      'git_repo', 'https://github.com/infosave2007/aivpn.git'
    )
  ),
  NOW(),
  NOW()
WHERE NOT EXISTS (SELECT 1 FROM protocols WHERE slug = 'aivpn');

-- 2. Add protocol variables for AIVPN
INSERT INTO protocol_variables (protocol_id, variable_name, variable_type, default_value, description, required)
SELECT p.id, 'connection_key', 'string', '', 'AIVPN connection key (generated by server)', true
FROM protocols p WHERE p.slug = 'aivpn'
  AND NOT EXISTS (SELECT 1 FROM protocol_variables WHERE protocol_id = p.id AND variable_name = 'connection_key');

INSERT INTO protocol_variables (protocol_id, variable_name, variable_type, default_value, description, required)
SELECT p.id, 'server_host', 'string', '', 'Server hostname or IP', true
FROM protocols p WHERE p.slug = 'aivpn'
  AND NOT EXISTS (SELECT 1 FROM protocol_variables WHERE protocol_id = p.id AND variable_name = 'server_host');

INSERT INTO protocol_variables (protocol_id, variable_name, variable_type, default_value, description, required)
SELECT p.id, 'server_port', 'number', '443', 'AIVPN server port', true
FROM protocols p WHERE p.slug = 'aivpn'
  AND NOT EXISTS (SELECT 1 FROM protocol_variables WHERE protocol_id = p.id AND variable_name = 'server_port');

-- 3. Add default template for AIVPN
INSERT INTO protocol_templates (protocol_id, template_name, template_content, is_default)
SELECT p.id, 'Default AIVPN', 'aivpn://{{connection_key}}', true
FROM protocols p WHERE p.slug = 'aivpn'
  AND NOT EXISTS (SELECT 1 FROM protocol_templates WHERE protocol_id = p.id AND template_name = 'Default AIVPN');

-- 4. Add translations for AIVPN
INSERT INTO translations (locale, category, key_name, translation) VALUES
('en', 'protocols', 'protocol_aivpn', 'AIVPN (AI-Powered)')
ON DUPLICATE KEY UPDATE translation = VALUES(translation);

INSERT INTO translations (locale, category, key_name, translation) VALUES
('ru', 'protocols', 'protocol_aivpn', 'AIVPN (ИИ-протокол)')
ON DUPLICATE KEY UPDATE translation = VALUES(translation);
