#!/bin/bash
# amnezia-himarc-setup - Setup script for Amnezia HiMarc GUI
# Version: 1.0.4
# Date: August 2026
# License: GPL-3.0-or-later

set -e
set -o pipefail

# Color definitions
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
MAGENTA='\033[0;35m'
CYAN='\033[0;36m'
NC='\033[0m'

# Version
VERSION="1.0.4"

# Configuration
CONFIG_DIR="/etc/amnezia-himarc"
DATA_DIR="/root/.wg-easy"
IMAGE="ghcr.io/nonenulldev404/wgandamneziawg-easy:latest"
CONTAINER_NAME="amnezia-himarc-server"
DEFAULT_USER="admin"
LOG_FILE="/var/log/amnezia-himarc/setup.log"
IP_INI_FILE="$CONFIG_DIR/ip.ini"

# Ensure directories exist with proper permissions
sudo mkdir -p "$(dirname "$LOG_FILE")" 2>/dev/null || true
sudo mkdir -p "/etc/amnezia/amneziawg" 2>/dev/null || true
sudo mkdir -p "$CONFIG_DIR" 2>/dev/null || true

# Logging function
log() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $*" | sudo tee -a "$LOG_FILE" 2>/dev/null || echo "[$(date '+%Y-%m-%d %H:%M:%S')] $*"
}

# Function: Load configuration from ip.ini
load_ip_ini() {
    if [[ -f "$IP_INI_FILE" ]]; then
        echo -e "${BLUE}📂 Loading configuration from ip.ini...${NC}"
        log "Loading configuration from ip.ini"
        
        # Parse INI file and export variables
        while IFS= read -r line; do
            # Skip comments and empty lines
            [[ "$line" =~ ^[[:space:]]*# ]] && continue
            [[ -z "$line" ]] && continue
            
            # Skip sections
            [[ "$line" =~ ^[[:space:]]*\[([^]]+)\] ]] && continue
            
            # Parse key=value
            if [[ "$line" =~ ^[[:space:]]*([^=]+)[[:space:]]*=[[:space:]]*(.*)$ ]]; then
                key="${BASH_REMATCH[1]}"
                value="${BASH_REMATCH[2]}"
                # Remove quotes and trim whitespace
                value=$(echo "$value" | sed "s/^['\"]//;s/['\"]$//" | xargs)
                # Export as environment variable
                export "$key"="$value"
                
                # Also set specific variables for script use
                case "$key" in
                    WG_HOST) LOADED_HOST="$value" ;;
                    PORT) LOADED_PORT="$value" ;;
                    WG_PORT) LOADED_WG_PORT="$value" ;;
                    USERNAME_HASH) LOADED_USERNAME_HASH="$value" ;;
                    PASSWORD_HASH) LOADED_PASSWORD_HASH="$value" ;;
                    JC) LOADED_JC="$value" ;;
                    JMIN) LOADED_JMIN="$value" ;;
                    JMAX) LOADED_JMAX="$value" ;;
                    H1) LOADED_H1="$value" ;;
                    H2) LOADED_H2="$value" ;;
                    H3) LOADED_H3="$value" ;;
                    H4) LOADED_H4="$value" ;;
                    UI_CHART_TYPE) LOADED_UI_CHART_TYPE="$value" ;;
                    UI_DARK_MODE) LOADED_UI_DARK_MODE="$value" ;;
                    LOG_LEVEL) LOADED_LOG_LEVEL="$value" ;;
                esac
            fi
        done < "$IP_INI_FILE"
        
        echo -e "${GREEN}✅ Configuration loaded from ip.ini${NC}"
        log "Configuration loaded from ip.ini"
        return 0
    else
        echo -e "${YELLOW}⚠️  ip.ini not found, using default values${NC}"
        log "ip.ini not found"
        return 1
    fi
}

# Function: Save configuration to ip.ini
save_ip_ini() {
    local SERVER_IP="$1"
    local USERNAME="$2"
    local PASSWORD="$3"
    local USERNAME_HASH="$4"
    local PASSWORD_HASH="$5"
    
    echo -e "${YELLOW}📝 Saving configuration to ip.ini...${NC}"
    log "Saving configuration to ip.ini"
    
    # Clean up hashes - remove any whitespace or newlines
    USERNAME_HASH=$(echo "$USERNAME_HASH" | tr -d ' \t\n\r' | head -1)
    PASSWORD_HASH=$(echo "$PASSWORD_HASH" | tr -d ' \t\n\r' | head -1)
    
    sudo tee "$IP_INI_FILE" > /dev/null << EOF
# Amnezia HiMarc Server Configuration
# Generated by amnezia-himarc-setup
# DO NOT SHARE THIS FILE - Contains sensitive credentials
# Generated: $(date)

[Server]
# Server IP address or domain name
WG_HOST=$SERVER_IP
# Web interface port (default: 51821)
PORT=${LOADED_PORT:-51821}
# WireGuard/AmneziaWG port (default: 51820)
WG_PORT=${LOADED_WG_PORT:-51820}

[Credentials]
# Bcrypt/SHA256 hashed credentials - DO NOT MODIFY MANUALLY
USERNAME_HASH='$USERNAME_HASH'
PASSWORD_HASH='$PASSWORD_HASH'

[AmneziaWG]
# Obfuscation parameters for AmneziaWG
JC=${LOADED_JC:-5}
JMIN=${LOADED_JMIN:-50}
JMAX=${LOADED_JMAX:-1000}
H1=${LOADED_H1:-1234567891}
H2=${LOADED_H2:-1234567892}
H3=${LOADED_H3:-1234567893}
H4=${LOADED_H4:-1234567894}

[UI]
# Chart type: 1=Real-time, 2=Historical
UI_CHART_TYPE=${LOADED_UI_CHART_TYPE:-1}
# Dark mode: auto, light, dark
UI_DARK_MODE=${LOADED_UI_DARK_MODE:-auto}
# Log level: info, debug, warn, error
LOG_LEVEL=${LOADED_LOG_LEVEL:-info}

[Network]
# Client network settings
CLIENT_SUBNET=10.8.0.0/24
DNS=1.1.1.1,8.8.8.8

[Backup]
BACKUP_RETENTION=7
BACKUP_DIR=/var/lib/amnezia-himarc/backups

[Monitoring]
HEALTH_CHECK_INTERVAL=300
HEALTH_CHECK_TIMEOUT=10
HEALTH_CHECK_RETRIES=3
EOF
    
    sudo chmod 600 "$IP_INI_FILE"
    echo -e "${GREEN}✅ Configuration saved to ip.ini${NC}"
    log "Configuration saved to ip.ini"
}

# Function: Convert ip.ini to .env for docker-compose
convert_ip_ini_to_env() {
    echo -e "${YELLOW}🔄 Converting ip.ini to .env for Docker Compose...${NC}"
    log "Converting ip.ini to .env"
    
    local ENV_FILE="$CONFIG_DIR/.env"
    
    # Clear existing .env file
    sudo bash -c "> \"$ENV_FILE\""
    
    # Parse ip.ini and create .env
    while IFS= read -r line; do
        # Skip comments and empty lines
        [[ "$line" =~ ^[[:space:]]*# ]] && continue
        [[ -z "$line" ]] && continue
        
        # Skip sections
        [[ "$line" =~ ^[[:space:]]*\[([^]]+)\] ]] && continue
        
        # Parse key=value
        if [[ "$line" =~ ^[[:space:]]*([^=]+)[[:space:]]*=[[:space:]]*(.*)$ ]]; then
            key="${BASH_REMATCH[1]}"
            value="${BASH_REMATCH[2]}"
            # Remove quotes and trim
            value=$(echo "$value" | sed "s/^['\"]//;s/['\"]$//" | xargs)
            # Write to .env file
            echo "$key=$value" | sudo tee -a "$ENV_FILE" > /dev/null
        fi
    done < "$IP_INI_FILE"
    
    sudo chmod 600 "$ENV_FILE"
    echo -e "${GREEN}✅ .env file created from ip.ini${NC}"
    log ".env file created"
}

# Parse arguments
NO_INTERACTION=false
CUSTOM_HOST=""
CUSTOM_USERNAME=""
CUSTOM_PASSWORD=""
SHOW_VERSION=false

while [[ $# -gt 0 ]]; do
    case $1 in
        --no-interaction) NO_INTERACTION=true ;;
        --host) CUSTOM_HOST="$2"; shift ;;
        --username) CUSTOM_USERNAME="$2"; shift ;;
        --password) CUSTOM_PASSWORD="$2"; shift ;;
        --version) SHOW_VERSION=true ;;
        --help) 
            cat << EOF
Usage: $0 [OPTIONS]

Options:
  --no-interaction    Run without prompts
  --host IP          Set server IP address
  --username USER    Set admin username (default: admin)
  --password PASS    Set admin password (auto-generated if not set)
  --version          Show version information
  --help             Show this help message

Examples:
  $0
  $0 --no-interaction --host 192.168.1.100
  $0 --host vpn.example.com --username admin --password MySecurePass123

For more information, see the man page:
  man amnezia-himarc-setup
EOF
            exit 0
            ;;
        *) echo -e "${RED}❌ Unknown option: $1${NC}"; exit 1 ;;
    esac
    shift
done

if [[ "$SHOW_VERSION" == true ]]; then
    echo "Amnezia HiMarc Server Setup v$VERSION"
    echo "Copyright (c) 2026 Alex S.Shubin"
    exit 0
fi

# Welcome banner
echo -e "${BLUE}═══════════════════════════════════════════════════════════════${NC}"
echo -e "${GREEN}🚀 Amnezia HiMarc Server Setup v$VERSION${NC}"
echo -e "${GREEN}   August 2026${NC}"
echo -e "${BLUE}═══════════════════════════════════════════════════════════════${NC}"
log "Starting setup process"

# Load existing configuration if available
load_ip_ini

# Function: Check command
check_command() {
    if ! command -v "$1" &> /dev/null; then
        echo -e "${YELLOW}⚠️  $1 not found${NC}"
        return 1
    fi
    echo -e "${GREEN}✅ $1 found${NC}"
    return 0
}

# Function: Check system requirements
check_requirements() {
    echo -e "${BLUE}📋 Checking system requirements...${NC}"
    log "Checking system requirements"
    
    # Check OS
    if ! grep -q "openSUSE" /etc/os-release 2>/dev/null; then
        echo -e "${YELLOW}⚠️  Not running on openSUSE. Compatibility may vary.${NC}"
        log "Warning: Not running on openSUSE"
    fi
    
    # Check kernel version
    KERNEL_VERSION=$(uname -r | cut -d. -f1-2)
    log "Kernel version: $KERNEL_VERSION"
    
    # Check Docker
    if ! check_command docker; then
        echo -e "${YELLOW}📦 Installing Docker...${NC}"
        log "Installing Docker"
        sudo zypper install -y docker
        sudo systemctl enable --now docker
        echo -e "${GREEN}✅ Docker installed${NC}"
    fi
    
    # Check Docker Compose V2
    if ! docker compose version &>/dev/null; then
        echo -e "${YELLOW}📦 Installing Docker Compose...${NC}"
        log "Installing Docker Compose"
        sudo zypper install -y docker-compose-switch || sudo zypper install -y docker-compose
        echo -e "${GREEN}✅ Docker Compose installed${NC}"
    fi
    
    # Check OpenSSL
    if ! check_command openssl; then
        echo -e "${YELLOW}📦 Installing OpenSSL...${NC}"
        log "Installing OpenSSL"
        sudo zypper install -y openssl
    fi
    
    # Check curl
    if ! check_command curl; then
        echo -e "${YELLOW}📦 Installing curl...${NC}"
        log "Installing curl"
        sudo zypper install -y curl
    fi
    
    # Check bc
    if ! check_command bc; then
        echo -e "${YELLOW}📦 Installing bc...${NC}"
        log "Installing bc"
        sudo zypper install -y bc
    fi
    
    # Check if Docker is running
    if ! sudo systemctl is-active --quiet docker; then
        echo -e "${YELLOW}⚠️  Docker is not running. Starting...${NC}"
        log "Starting Docker"
        sudo systemctl start docker
        sudo systemctl enable docker
    fi
    
    # Check Docker socket
    if [[ ! -S /var/run/docker.sock ]]; then
        echo -e "${RED}❌ Docker socket not found. Docker may not be installed correctly.${NC}"
        log "Docker socket not found"
        exit 1
    fi
    
    # Check if user is in docker group
    if ! groups | grep -q docker; then
        echo -e "${YELLOW}⚠️  User not in docker group. Adding...${NC}"
        log "Adding user to docker group"
        sudo usermod -aG docker "$USER"
        echo -e "${YELLOW}⚠️  Please log out and back in for group changes to take effect.${NC}"
        echo -e "${YELLOW}    Or run: newgrp docker${NC}"
        log "User added to docker group"
    fi
    
    # Check if WireGuard module is loaded
    if ! lsmod | grep -q wireguard; then
        echo -e "${YELLOW}⚠️  WireGuard kernel module not loaded.${NC}"
        log "Warning: WireGuard kernel module not loaded"
        echo -e "${CYAN}   You may need to: sudo modprobe wireguard${NC}"
        echo -e "${CYAN}   Or install wireguard-tools: sudo zypper install wireguard-tools${NC}"
    fi
    
    echo -e "${GREEN}✅ System requirements OK${NC}"
    log "System requirements OK"
}

# Function: Configure firewall
configure_firewall() {
    echo -e "${BLUE}🔥 Configuring firewall...${NC}"
    log "Configuring firewall"
    
    local FIREWALL_CONFIGURED=false
    
    if command -v firewall-cmd &>/dev/null; then
        echo -e "${CYAN}   Using firewalld...${NC}"
        sudo firewall-cmd --add-port=51820/udp --add-port=51821/tcp --permanent 2>/dev/null || true
        sudo firewall-cmd --reload 2>/dev/null || true
        FIREWALL_CONFIGURED=true
        echo -e "${GREEN}✅ Firewalld configured${NC}"
        log "Firewalld configured"
    elif command -v ufw &>/dev/null; then
        echo -e "${CYAN}   Using UFW...${NC}"
        sudo ufw allow 51820/udp 2>/dev/null || true
        sudo ufw allow 51821/tcp 2>/dev/null || true
        FIREWALL_CONFIGURED=true
        echo -e "${GREEN}✅ UFW configured${NC}"
        log "UFW configured"
    else
        echo -e "${YELLOW}⚠️  No firewall detected. Please configure manually.${NC}"
        log "No firewall detected"
        echo -e "${CYAN}   Required ports: 51820/udp, 51821/tcp${NC}"
    fi
}

# Function: Get server IP
get_server_ip() {
    if [[ -n "$CUSTOM_HOST" ]]; then
        echo "$CUSTOM_HOST"
        return
    fi
    
    # Check if loaded from ip.ini
    if [[ -n "$LOADED_HOST" ]]; then
        echo "$LOADED_HOST"
        return
    fi
    
    echo -e "${BLUE}🌐 Detecting server IP...${NC}" >&2
    log "Detecting server IP"
    
    local IP=""
    # Try multiple services
    for service in "ifconfig.me" "icanhazip.com" "ipecho.net/plain" "api.ipify.org"; do
        echo -e "${CYAN}   Trying $service...${NC}" >&2
        IP=$(curl -s --max-time 5 "https://$service" 2>/dev/null)
        if [[ -n "$IP" ]] && [[ "$IP" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
            echo -e "${GREEN}   ✅ Got IP: $IP${NC}" >&2
            break
        fi
    done
    
    # Fallback to local IP
    if [[ -z "$IP" ]]; then
        echo -e "${YELLOW}   Trying local IP detection...${NC}" >&2
        IP=$(hostname -I | awk '{print $1}')
        if [[ -z "$IP" ]]; then
            IP="localhost"
            echo -e "${RED}   ❌ Could not detect IP. Using localhost${NC}" >&2
            log "Could not detect IP"
        else
            echo -e "${GREEN}   ✅ Got local IP: $IP${NC}" >&2
        fi
    fi
    
    echo -e "${GREEN}📍 Server IP: $IP${NC}" >&2
    log "Server IP: $IP"
    echo "$IP"
}

# Function: Generate secure password
generate_password() {
    if [[ -n "$CUSTOM_PASSWORD" ]]; then
        echo "$CUSTOM_PASSWORD"
    else
        # Generate secure password with special characters
        openssl rand -base64 16 | tr -d '/+=' | head -c16
    fi
}

# Function: Check if ports are available
check_ports() {
    echo -e "${BLUE}🔌 Checking ports...${NC}"
    log "Checking ports"
    
    local PORTS_OK=true
    
    if ss -tuln 2>/dev/null | grep -q ":51820 "; then
        echo -e "${RED}❌ Port 51820/udp is already in use${NC}"
        log "Port 51820 in use"
        PORTS_OK=false
    fi
    
    if ss -tuln 2>/dev/null | grep -q ":51821 "; then
        echo -e "${RED}❌ Port 51821/tcp is already in use${NC}"
        log "Port 51821 in use"
        PORTS_OK=false
    fi
    
    if [[ "$PORTS_OK" == false ]]; then
        echo -e "${YELLOW}⚠️  Port conflicts detected. Please free the ports or use different ports.${NC}"
        if [[ "$NO_INTERACTION" == true ]]; then
            echo -e "${RED}❌ Cannot continue due to port conflicts${NC}"
            exit 1
        fi
        read -p "Continue anyway? (y/n) [n]: " -n 1 -r
        echo
        if [[ ! $REPLY =~ ^[Yy]$ ]]; then
            exit 1
        fi
    else
        echo -e "${GREEN}✅ All ports are available${NC}"
        log "Ports are available"
    fi
}

# Function: Generate hash
generate_hash() {
    local input="$1"
    local hash=""
    
    # Try bcrypt via docker
    hash=$(sudo docker run --rm "$IMAGE" wgpw "$input" 2>/dev/null | tail -1 | tr -d '\n\r' | xargs)
    if [[ -n "$hash" ]] && [[ "$hash" =~ ^\$2[ayb]\$.+$ ]]; then
        echo "$hash"
        return 0
    fi
    
    # Fallback: SHA256
    echo -e "${YELLOW}⚠️  Using SHA256 fallback for hashing (less secure)${NC}" >&2
    echo -n "$input" | sha256sum | awk '{print $1}' | tr -d '\n\r'
}

# Function: Setup container
setup_container() {
    local SERVER_IP="$1"
    local USERNAME="$2"
    local PASSWORD="$3"
    
    echo -e "${BLUE}🐳 Setting up container...${NC}"
    log "Setting up container"
    
    # Create data directory
    sudo mkdir -p "$DATA_DIR"
    sudo mkdir -p "/etc/amnezia/amneziawg"
    
    # Check if Docker is running
    if ! sudo docker ps &>/dev/null; then
        echo -e "${RED}❌ Docker is not responding. Check if Docker daemon is running.${NC}"
        log "Docker not responding"
        echo -e "${YELLOW}   Try: sudo systemctl start docker${NC}"
        exit 1
    fi
    
    # Pull the image
    echo -e "${YELLOW}📥 Pulling image...${NC}"
    log "Pulling image: $IMAGE"
    if ! sudo docker pull "$IMAGE" 2>&1 | sudo tee -a "$LOG_FILE"; then
        echo -e "${RED}❌ Failed to pull image. Check Docker.${NC}"
        log "Failed to pull image"
        exit 1
    fi
    echo -e "${GREEN}✅ Image pulled successfully${NC}"
    
    # Generate hashes
    echo -e "${YELLOW}🔐 Generating credentials...${NC}"
    log "Generating credentials"
    
    sleep 2
    
    local USERNAME_HASH=$(generate_hash "$USERNAME")
    local PASSWORD_HASH=$(generate_hash "$PASSWORD")
    
    if [[ -z "$USERNAME_HASH" ]] || [[ -z "$PASSWORD_HASH" ]]; then
        echo -e "${RED}❌ Failed to generate hashes${NC}"
        log "Failed to generate hashes"
        exit 1
    fi
    
    # Clean up hashes
    USERNAME_HASH=$(echo "$USERNAME_HASH" | tr -d ' \t\n\r' | xargs)
    PASSWORD_HASH=$(echo "$PASSWORD_HASH" | tr -d ' \t\n\r' | xargs)
    
    echo -e "${GREEN}✅ Credentials generated${NC}"
    log "Credentials generated"
    
    # Save configuration
    save_ip_ini "$SERVER_IP" "$USERNAME" "$PASSWORD" "$USERNAME_HASH" "$PASSWORD_HASH"
    
    # Convert to .env
    convert_ip_ini_to_env
    
    # Get variables
    local PORT="${LOADED_PORT:-51821}"
    local WG_PORT="${LOADED_WG_PORT:-51820}"
    local JC="${LOADED_JC:-5}"
    local JMIN="${LOADED_JMIN:-50}"
    local JMAX="${LOADED_JMAX:-1000}"
    local H1="${LOADED_H1:-1234567891}"
    local H2="${LOADED_H2:-1234567892}"
    local H3="${LOADED_H3:-1234567893}"
    local H4="${LOADED_H4:-1234567894}"
    local UI_CHART_TYPE="${LOADED_UI_CHART_TYPE:-1}"
    local UI_DARK_MODE="${LOADED_UI_DARK_MODE:-auto}"
    local LOG_LEVEL="${LOADED_LOG_LEVEL:-info}"
    
    # Create docker-compose.yml
    echo -e "${YELLOW}📝 Creating docker-compose.yml...${NC}"
    log "Creating docker-compose.yml"
    
    sudo cat > "$CONFIG_DIR/docker-compose.yml" << YAMLEOF
version: "3.8"

services:
  amnezia-himarc:
    image: ghcr.io/nonenulldev404/wgandamneziawg-easy:latest
    container_name: amnezia-himarc-server
    restart: unless-stopped
    environment:
      LANG: ru
      WG_HOST: ${SERVER_IP}
      USERNAME_HASH: '${USERNAME_HASH}'
      PASSWORD_HASH: '${PASSWORD_HASH}'
      PORT: ${PORT}
      WG_PORT: ${WG_PORT}
      JC: ${JC}
      JMIN: ${JMIN}
      JMAX: ${JMAX}
      H1: ${H1}
      H2: ${H2}
      H3: ${H3}
      H4: ${H4}
      UI_CHART_TYPE: ${UI_CHART_TYPE}
      UI_DARK_MODE: ${UI_DARK_MODE}
      LOG_LEVEL: ${LOG_LEVEL}
    volumes:
      - /etc/amnezia/amneziawg:/etc/amnezia/amneziawg
      - ${DATA_DIR}:/etc/wireguard
      - /proc/sys/net:/proc/sys/net:ro
    ports:
      - "${WG_PORT}:51820/udp"
      - "${PORT}:51821/tcp"
    cap_add:
      - NET_ADMIN
      - SYS_MODULE
    sysctls:
      - net.ipv4.conf.all.src_valid_mark=1
      - net.ipv4.ip_forward=1
    devices:
      - /dev/net/tun:/dev/net/tun
    logging:
      driver: "json-file"
      options:
        max-size: "10m"
        max-file: "3"
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost:${PORT}/api/health"]
      interval: 30s
      timeout: 10s
      retries: 3
      start_period: 40s
    deploy:
      resources:
        limits:
          cpus: "1"
          memory: 512M
        reservations:
          cpus: "0.25"
          memory: 256M

volumes:
  wg-config:
    name: amnezia-himarc-wg-config
YAMLEOF
    
    echo -e "${GREEN}✅ docker-compose.yml created${NC}"
    log "docker-compose.yml created"
    
    # Verify YAML syntax
    echo -e "${YELLOW}🔍 Verifying YAML syntax...${NC}"
    if ! cd "$CONFIG_DIR" 2>/dev/null || ! sudo docker compose config &>/dev/null; then
        echo -e "${RED}❌ Invalid YAML syntax in docker-compose.yml${NC}"
        log "Invalid YAML syntax"
        echo -e "${YELLOW}   Checking file contents:${NC}"
        sudo cat "$CONFIG_DIR/docker-compose.yml"
        exit 1
    fi
    echo -e "${GREEN}✅ YAML syntax OK${NC}"
    
    # Stop existing container
    cd "$CONFIG_DIR" || exit 1
    echo -e "${YELLOW}🔄 Stopping existing container (if any)...${NC}"
    sudo docker compose down 2>/dev/null || true
    
    # Start the stack
    echo -e "${YELLOW}🚀 Starting container...${NC}"
    log "Starting container"
    if ! sudo docker compose up -d 2>&1 | sudo tee -a "$LOG_FILE"; then
        echo -e "${RED}❌ Failed to start container. Check logs:${NC}"
        log "Failed to start container"
        sudo docker logs "$CONTAINER_NAME" 2>/dev/null || true
        exit 1
    fi
    
    # Wait for container
    echo -e "${YELLOW}⏳ Waiting for container to be ready...${NC}"
    log "Waiting for container to be ready"
    local max_attempts=30
    local attempt=0
    
    while ! sudo docker ps --filter "name=$CONTAINER_NAME" --filter "status=running" | grep -q "$CONTAINER_NAME"; do
        attempt=$((attempt + 1))
        echo -ne "${CYAN}   Starting container: attempt $attempt/$max_attempts...${NC}\r"
        if [[ $attempt -ge $max_attempts ]]; then
            echo
            echo -e "${RED}❌ Container failed to start${NC}"
            log "Container failed to start"
            sudo docker logs "$CONTAINER_NAME" --tail 20
            exit 1
        fi
        sleep 2
    done
    echo
    
    # Wait for health check
    echo -e "${YELLOW}⏳ Waiting for health check...${NC}"
    attempt=0
    while true; do
        attempt=$((attempt + 1))
        HEALTH_STATUS=$(sudo docker inspect --format='{{.State.Health.Status}}' "$CONTAINER_NAME" 2>/dev/null || echo "none")
        
        if [[ "$HEALTH_STATUS" == "healthy" ]]; then
            echo -e "${GREEN}✅ Container is healthy!${NC}"
            break
        elif [[ "$HEALTH_STATUS" == "unhealthy" ]]; then
            echo
            echo -e "${RED}❌ Container is unhealthy${NC}"
            log "Container is unhealthy"
            sudo docker logs "$CONTAINER_NAME" --tail 20
            exit 1
        elif [[ $attempt -ge $max_attempts ]]; then
            echo
            echo -e "${YELLOW}⚠️  Health check timeout, but container is running${NC}"
            log "Health check timeout"
            break
        fi
        
        echo -ne "${CYAN}   Health check: $HEALTH_STATUS (attempt $attempt/$max_attempts)...${NC}\r"
        sleep 2
    done
    echo
    
    # Enable auto-recovery watcher
    if command -v systemctl &>/dev/null; then
        echo -e "${YELLOW}🔄 Enabling auto-recovery watcher...${NC}"
        log "Enabling auto-recovery watcher"
        sudo systemctl daemon-reload 2>/dev/null || true
        sudo systemctl enable amnezia-himarc-watcher.timer 2>/dev/null || true
        sudo systemctl start amnezia-himarc-watcher.timer 2>/dev/null || true
        echo -e "${GREEN}✅ Auto-recovery watcher enabled${NC}"
        log "Auto-recovery watcher enabled"
    fi
}

# Function: Display completion message
show_completion() {
    local SERVER_IP="$1"
    local USERNAME="$2"
    local PASSWORD="$3"
    
    echo
    echo -e "${GREEN}═══════════════════════════════════════════════════════════════${NC}"
    echo -e "${GREEN}✅ Amnezia HiMarc Server is ready!${NC}"
    echo -e "${GREEN}✅ Amnezia HiMarc Server готов к работе!${NC}"
    echo -e "${GREEN}═══════════════════════════════════════════════════════════════${NC}"
    echo
    echo -e "${BLUE}🌐 Web Interface / Веб-интерфейс:${NC}"
    echo -e "   ${GREEN}http://$SERVER_IP:${LOADED_PORT:-51821}${NC}"
    echo
    echo -e "${BLUE}🔑 Login Credentials / Учетные данные:${NC}"
    echo -e "   Username: ${GREEN}$USERNAME${NC}"
    echo -e "   Password: ${GREEN}$PASSWORD${NC}"
    echo
    echo -e "${YELLOW}⚠️  IMPORTANT: Save these credentials securely!${NC}"
    echo -e "${YELLOW}   Credentials saved in: $IP_INI_FILE${NC}"
    echo -e "${YELLOW}   To view: sudo cat $IP_INI_FILE${NC}"
    echo
    echo -e "${BLUE}📁 Configuration Location / Расположение конфигурации:${NC}"
    echo -e "   ${GREEN}$CONFIG_DIR/${NC}"
    echo -e "   ${GREEN}$IP_INI_FILE${NC}"
    echo
    echo -e "${BLUE}📁 Data Location / Расположение данных:${NC}"
    echo -e "   ${GREEN}$DATA_DIR/${NC}"
    echo
    echo -e "${BLUE}🛠️ Useful Commands / Полезные команды:${NC}"
    echo -e "   View logs:      ${GREEN}docker logs $CONTAINER_NAME -f${NC}"
    echo -e "   Restart:        ${GREEN}cd $CONFIG_DIR && docker compose restart${NC}"
    echo -e "   Remote restart: ${GREEN}sudo systemctl reload amnezia-himarc${NC}"
    echo -e "   Stop:           ${GREEN}cd $CONFIG_DIR && docker compose down${NC}"
    echo -e "   Start:          ${GREEN}cd $CONFIG_DIR && docker compose up -d${NC}"
    echo -e "   Update:         ${GREEN}cd $CONFIG_DIR && docker compose pull && docker compose up -d${NC}"
    echo -e "   Status:         ${GREEN}docker ps | grep $CONTAINER_NAME${NC}"
    echo -e "   Health check:   ${GREEN}amnezia-himarc-healthcheck${NC}"
    echo -e "   Edit config:    ${GREEN}sudo nano $IP_INI_FILE${NC}"
    echo
    echo -e "${BLUE}🔄 Auto-recovery watcher (Автоматическое восстановление):${NC}"
    echo -e "   Status:         ${GREEN}systemctl status amnezia-himarc-watcher.timer${NC}"
    echo -e "   Logs:           ${GREEN}journalctl -u amnezia-himarc-watcher.service -f${NC}"
    echo
    echo -e "${BLUE}📊 Statistics / Статистика:${NC}"
    echo -e "   ${GREEN}docker stats $CONTAINER_NAME${NC}"
    echo
    echo -e "${GREEN}═══════════════════════════════════════════════════════════════${NC}"
}

# Function: Cleanup on failure
cleanup() {
    echo -e "${YELLOW}🔄 Cleaning up...${NC}"
    log "Cleaning up on failure"
    cd "$CONFIG_DIR" 2>/dev/null && sudo docker compose down 2>/dev/null || true
    exit 1
}

# Trap errors
trap cleanup ERR

# Main execution
main() {
    log "=== Starting Amnezia HiMarc Server Setup v$VERSION ==="
    
    # Check requirements
    check_requirements
    
    # Check ports
    check_ports
    
    # Configure firewall
    if [[ "$NO_INTERACTION" != "true" ]]; then
        echo
        read -p "Configure firewall rules automatically? (y/n) [y]: " -n 1 -r
        echo
        if [[ $REPLY =~ ^[Yy]$ ]] || [[ -z $REPLY ]]; then
            configure_firewall
        else
            echo -e "${YELLOW}⚠️  Skipping firewall configuration${NC}"
            log "Skipping firewall configuration"
        fi
    else
        configure_firewall
    fi
    
    # Get server IP
    SERVER_IP=$(get_server_ip)
    
    # Set credentials
    USERNAME="${CUSTOM_USERNAME:-$DEFAULT_USER}"
    PASSWORD=$(generate_password)
    
    echo -e "${BLUE}🔑 Generated credentials:${NC}"
    echo -e "   Username: ${GREEN}$USERNAME${NC}"
    echo -e "   Password: ${GREEN}$PASSWORD${NC}"
    log "Username: $USERNAME"
    
    # Confirm before proceeding
    if [[ "$NO_INTERACTION" != "true" ]]; then
        echo
        read -p "Proceed with setup? (y/n) [y]: " -n 1 -r
        echo
        if [[ ! $REPLY =~ ^[Yy]$ ]] && [[ -n $REPLY ]]; then
            echo -e "${YELLOW}Setup cancelled${NC}"
            exit 0
        fi
    fi
    
    # Setup container
    setup_container "$SERVER_IP" "$USERNAME" "$PASSWORD"
    
    # Show completion
    show_completion "$SERVER_IP" "$USERNAME" "$PASSWORD"
    
    log "=== Setup completed successfully ==="
}

# Run main
main "$@"

# EOF