#!/bin/bash

# Script d'installation automatique pour serveur de production
# Usage: curl -fsSL https://raw.githubusercontent.com/.../install.sh | sudo bash
# Ou: sudo bash install.sh

set -e

echo "╔══════════════════════════════════════════════════════════════════╗"
echo "║   🎮 Installation automatique - Serveur NationsGlory Docker      ║"
echo "╚══════════════════════════════════════════════════════════════════╝"
echo ""

# Configuration
INSTALL_DIR="/srv/minecraft/moddé"
BACKUP_DIR="/srv/minecraft/backups"

# Couleurs
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Fonctions
log_info() {
    echo -e "${BLUE}ℹ${NC} $1"
}

log_success() {
    echo -e "${GREEN}✅${NC} $1"
}

log_warning() {
    echo -e "${YELLOW}⚠️${NC} $1"
}

log_error() {
    echo -e "${RED}❌${NC} $1"
}

# Vérification root
if [ "$EUID" -ne 0 ]; then 
    log_error "Ce script nécessite les droits root"
    echo "Relancer avec: sudo $0"
    exit 1
fi

echo "📋 Vérification du système..."
echo ""

# Vérifier l'OS
if [ -f /etc/os-release ]; then
    . /etc/os-release
    OS=$NAME
    VER=$VERSION_ID
    log_info "Système détecté: $OS $VER"
else
    log_warning "Système non identifié, continuation..."
fi

# Installation Docker
echo ""
log_info "Vérification de Docker..."

if ! command -v docker &> /dev/null; then
    log_warning "Docker n'est pas installé"
    read -p "Installer Docker? [Y/n] " -n 1 -r
    echo ""
    if [[ ! $REPLY =~ ^[Nn]$ ]]; then
        log_info "Installation de Docker..."
        curl -fsSL https://get.docker.com | sh
        systemctl enable docker
        systemctl start docker
        log_success "Docker installé"
    else
        log_error "Docker est requis. Installation annulée."
        exit 1
    fi
else
    log_success "Docker déjà installé ($(docker --version))"
fi

# Installation Docker Compose
echo ""
log_info "Vérification de Docker Compose..."

if ! command -v docker-compose &> /dev/null; then
    log_warning "Docker Compose n'est pas installé"
    log_info "Installation de Docker Compose..."
    
    if [ -f /etc/debian_version ]; then
        apt-get update -qq
        apt-get install -y -qq docker-compose
    elif [ -f /etc/redhat-release ]; then
        yum install -y docker-compose
    else
        # Installation via pip
        apt-get update -qq
        apt-get install -y -qq python3-pip
        pip3 install docker-compose
    fi
    
    log_success "Docker Compose installé"
else
    log_success "Docker Compose déjà installé ($(docker-compose --version))"
fi

# Création de la structure
echo ""
log_info "Création de la structure /srv/minecraft..."

mkdir -p /srv/minecraft/{moddé,proxy,survie,backups}
mkdir -p "$INSTALL_DIR"/{data,mods,plugins,config,libraries,backups}

log_success "Structure créée"

# Configuration du firewall (si UFW installé)
echo ""
if command -v ufw &> /dev/null; then
    log_info "Configuration du firewall..."
    ufw allow 25565/tcp comment "Minecraft NationsGlory" >/dev/null 2>&1 || true
    log_success "Port 25565 ouvert"
else
    log_warning "UFW non installé, configuration firewall manuelle requise"
fi

# Création des fichiers de configuration
echo ""
log_info "Création des fichiers de configuration..."

# .env
cat > "$INSTALL_DIR/.env" << 'EOF'
# Configuration NationsGlory
MEMORY=2G
INIT_MEMORY=1G
MINECRAFT_PORT=25565
MAX_PLAYERS=20
VIEW_DISTANCE=10
DIFFICULTY=peaceful
GAMEMODE=creative
LEVEL_TYPE=FLAT
SERVER_NAME=NationsGlory Moddé
MOTD=§6NationsGlory §8- §7Serveur Moddé 1.6.4
DEBUG=false
TZ=Europe/Paris
EOF

log_success "Fichier .env créé"

# docker-compose.yml
cat > "$INSTALL_DIR/docker-compose.yml" << 'EOF'
version: '3.8'

services:
  nationsglory-modded:
    image: itzg/minecraft-server:java8
    container_name: mc-nationsglory
    restart: unless-stopped
    
    environment:
      TYPE: "CUSTOM"
      CUSTOM_SERVER: "/data/mcpc.jar"
      MEMORY: "${MEMORY:-2G}"
      INIT_MEMORY: "${INIT_MEMORY:-1G}"
      JVM_OPTS: "-XX:+UseG1GC"
      EULA: "TRUE"
      ONLINE_MODE: "FALSE"
      DIFFICULTY: "${DIFFICULTY:-peaceful}"
      MODE: "${GAMEMODE:-creative}"
      LEVEL_TYPE: "${LEVEL_TYPE:-FLAT}"
      PVP: "FALSE"
      SPAWN_MONSTERS: "FALSE"
      SPAWN_NPCS: "TRUE"
      SPAWN_ANIMALS: "TRUE"
      ALLOW_FLIGHT: "TRUE"
      MAX_PLAYERS: "${MAX_PLAYERS:-20}"
      VIEW_DISTANCE: "${VIEW_DISTANCE:-10}"
      SERVER_NAME: "${SERVER_NAME:-NationsGlory}"
      MOTD: "${MOTD:-NationsGlory Serveur}"
      USE_AIKAR_FLAGS: "FALSE"
      DEBUG: "${DEBUG:-FALSE}"
      TZ: "${TZ:-Europe/Paris}"
    
    ports:
      - "${MINECRAFT_PORT:-25565}:25565"
    
    volumes:
      - ./data:/data
      - ./mods:/data/mods
      - ./plugins:/data/plugins
      - ./config:/data/config
      - ./world:/data/world
      - ./libraries:/data/libraries
    
    deploy:
      resources:
        limits:
          memory: 3G
        reservations:
          memory: 1G
    
    ulimits:
      nofile:
        soft: 65535
        hard: 65535
    
    networks:
      - minecraft-network

networks:
  minecraft-network:
    driver: bridge
EOF

log_success "Fichier docker-compose.yml créé"

# Makefile
cat > "$INSTALL_DIR/Makefile" << 'EOF'
.PHONY: start stop restart logs status backup

start:
	@docker-compose up -d
	@echo "✅ Serveur démarré"

stop:
	@docker-compose down
	@echo "✅ Serveur arrêté"

restart:
	@docker-compose restart
	@echo "✅ Serveur redémarré"

logs:
	@docker-compose logs -f --tail=100

status:
	@docker-compose ps
	@docker stats --no-stream mc-nationsglory 2>/dev/null || true

backup:
	@mkdir -p backups
	@docker-compose exec -T nationsglory-modded rcon-cli save-all flush || true
	@sleep 3
	@tar -czf backups/world-$(shell date +%Y%m%d-%H%M).tar.gz data/world/
	@echo "✅ Backup créé"

console:
	@docker-compose exec nationsglory-modded rcon-cli
EOF

log_success "Makefile créé"

# README rapide
cat > "$INSTALL_DIR/README.txt" << 'EOF'
╔══════════════════════════════════════════════════════════════════╗
║              🎮 Serveur NationsGlory - Docker                    ║
╚══════════════════════════════════════════════════════════════════╝

⚠️ AVANT DE DÉMARRER:

1. Copier mcpc.jar dans data/
2. Copier les mods dans mods/
3. Copier les plugins dans plugins/
4. Copier les configs dans config/
5. Copier les libraries dans libraries/

🚀 DÉMARRER:

  make start
  ou: docker-compose up -d

📊 VOIR LES LOGS:

  make logs
  ou: docker-compose logs -f

🛑 ARRÊTER:

  make stop
  ou: docker-compose down

📚 Documentation complète:
  https://github.com/votre-repo/DEPLOYMENT.md

EOF

log_success "README créé"

# Permissions
echo ""
log_info "Configuration des permissions..."

chown -R 1000:1000 "$INSTALL_DIR"
chmod -R 755 "$INSTALL_DIR"

log_success "Permissions configurées"

# Script de backup automatique
echo ""
log_info "Création du script de backup automatique..."

cat > /usr/local/bin/minecraft-backup.sh << 'EOF'
#!/bin/bash
cd /srv/minecraft/moddé
docker-compose exec -T nationsglory-modded rcon-cli save-all flush 2>/dev/null
sleep 5
tar -czf /srv/minecraft/backups/auto-$(date +%Y%m%d-%H%M).tar.gz data/world/
find /srv/minecraft/backups/ -name "auto-*.tar.gz" -mtime +7 -delete
echo "Backup terminé: $(date)" >> /var/log/minecraft-backup.log
EOF

chmod +x /usr/local/bin/minecraft-backup.sh

log_success "Script de backup créé: /usr/local/bin/minecraft-backup.sh"

# Cron pour backups automatiques
echo ""
read -p "Configurer des backups automatiques quotidiens à 3h? [Y/n] " -n 1 -r
echo ""
if [[ ! $REPLY =~ ^[Nn]$ ]]; then
    (crontab -l 2>/dev/null; echo "0 3 * * * /usr/local/bin/minecraft-backup.sh") | crontab -
    log_success "Backups automatiques configurés (3h du matin)"
fi

# Service systemd (optionnel)
echo ""
read -p "Créer un service systemd pour démarrage automatique? [Y/n] " -n 1 -r
echo ""
if [[ ! $REPLY =~ ^[Nn]$ ]]; then
    cat > /etc/systemd/system/minecraft-nationsglory.service << EOF
[Unit]
Description=NationsGlory Minecraft Server
Requires=docker.service
After=docker.service

[Service]
Type=oneshot
RemainAfterExit=yes
WorkingDirectory=$INSTALL_DIR
ExecStart=/usr/bin/docker-compose up -d
ExecStop=/usr/bin/docker-compose down
TimeoutStartSec=0

[Install]
WantedBy=multi-user.target
EOF

    systemctl daemon-reload
    systemctl enable minecraft-nationsglory.service
    log_success "Service systemd créé et activé"
fi

# Résumé final
echo ""
echo "╔══════════════════════════════════════════════════════════════════╗"
echo "║              ✅ INSTALLATION TERMINÉE !                          ║"
echo "╚══════════════════════════════════════════════════════════════════╝"
echo ""
log_info "Emplacement: $INSTALL_DIR"
log_info "Backups: $BACKUP_DIR"
echo ""
echo "📋 PROCHAINES ÉTAPES:"
echo ""
echo "1. Copier les fichiers du serveur:"
echo "   cd $INSTALL_DIR"
echo "   # Copier mcpc.jar, mods, plugins, config, libraries"
echo ""
echo "2. Démarrer le serveur:"
echo "   cd $INSTALL_DIR"
echo "   make start"
echo ""
echo "3. Voir les logs:"
echo "   make logs"
echo ""
echo "4. Se connecter:"
echo "   IP: $(hostname -I | awk '{print $1}'):25565"
echo "   Version: Minecraft 1.6.4"
echo ""
echo "📚 Aide:"
echo "   cd $INSTALL_DIR"
echo "   make help"
echo "   cat README.txt"
echo ""
log_success "Installation réussie !"
echo ""
