# ==============================================
# AZEROTHCORE DATABASE LAYER
# ==============================================

services:
  # Step 1: MySQL database
  ac-mysql:
    image: ${MYSQL_IMAGE}
    container_name: ${CONTAINER_MYSQL}
    environment:
      MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD}
      MYSQL_ROOT_HOST: '${MYSQL_ROOT_HOST}'
      MYSQL_ALLOW_EMPTY_PASSWORD: no
      MYSQL_DATADIR: /var/lib/mysql-runtime
      # MySQL configuration variables for startup script
      MYSQL_CHARACTER_SET: ${MYSQL_CHARACTER_SET}
      MYSQL_COLLATION: ${MYSQL_COLLATION}
      MYSQL_MAX_CONNECTIONS: ${MYSQL_MAX_CONNECTIONS}
      MYSQL_INNODB_BUFFER_POOL_SIZE: ${MYSQL_INNODB_BUFFER_POOL_SIZE}
      MYSQL_INNODB_LOG_FILE_SIZE: ${MYSQL_INNODB_LOG_FILE_SIZE}
    ports:
      - "${MYSQL_EXTERNAL_PORT}:${MYSQL_PORT}"
    volumes:
      - ${STORAGE_PATH}/mysql-data:/var/lib/mysql-persistent
      - ${HOST_BACKUP_PATH}:/backups
    tmpfs:
      - /var/lib/mysql-runtime:size=2G
    command:
      - mysqld
      - --datadir=/var/lib/mysql-runtime
      - --default-authentication-plugin=mysql_native_password
      - --character-set-server=utf8mb4
      - --collation-server=utf8mb4_unicode_ci
      - --max_connections=1000
      - --innodb-buffer-pool-size=256M
      - --innodb-log-file-size=64M
    restart: unless-stopped
    healthcheck:
      test: ["CMD", "sh", "-c", "mysqladmin ping -h localhost -u ${MYSQL_USER} -p${MYSQL_ROOT_PASSWORD} --silent || exit 1"]
      interval: ${MYSQL_HEALTHCHECK_INTERVAL}
      timeout: ${MYSQL_HEALTHCHECK_TIMEOUT}
      retries: ${MYSQL_HEALTHCHECK_RETRIES}
      start_period: ${MYSQL_HEALTHCHECK_START_PERIOD}
    networks:
      - azerothcore

  # Step 2: Backup service
  ac-backup:
    image: ${MYSQL_IMAGE}
    container_name: ${CONTAINER_BACKUP}
    depends_on:
      ac-db-import:
        condition: service_completed_successfully
    environment:
      MYSQL_HOST: ${CONTAINER_MYSQL}
      MYSQL_PORT: ${MYSQL_PORT}
      MYSQL_USER: ${MYSQL_USER}
      MYSQL_PASSWORD: ${MYSQL_ROOT_PASSWORD}
      BACKUP_RETENTION_DAYS: ${BACKUP_RETENTION_DAYS}
      BACKUP_RETENTION_HOURS: ${BACKUP_RETENTION_HOURS}
      BACKUP_DAILY_TIME: ${BACKUP_DAILY_TIME}
      DB_AUTH_NAME: ${DB_AUTH_NAME}
      DB_WORLD_NAME: ${DB_WORLD_NAME}
      DB_CHARACTERS_NAME: ${DB_CHARACTERS_NAME}
      TZ: ${TZ}
    volumes:
      - ${HOST_BACKUP_PATH}:/backups
    working_dir: /tmp
    command:
      - /bin/bash
      - -c
      - |
        # Install curl for downloading backup scheduler script (handle different package managers)
        microdnf install -y curl || yum install -y curl || (apt-get update && apt-get install -y curl)

        # Download backup scheduler script from GitHub
        echo "📥 Downloading backup scheduler script from GitHub..."
        curl -fsSL https://raw.githubusercontent.com/uprightbass360/acore-compose/main/scripts/backup-scheduler.sh -o /tmp/backup-scheduler.sh
        chmod +x /tmp/backup-scheduler.sh
        /tmp/backup-scheduler.sh
    restart: unless-stopped
    networks:
      - azerothcore

  # Step 3: Database initialization (conditional - only runs if import fails)
  ac-db-init:
    image: ${MYSQL_IMAGE}
    container_name: ${CONTAINER_DB_INIT}
    depends_on:
      ac-db-import:
        condition: service_completed_successfully
    volumes:
      - ${STORAGE_PATH}/mysql-data:/var/lib/mysql-persistent
      - ${HOST_BACKUP_PATH}:/backups
    networks:
      - azerothcore
    environment:
      MYSQL_PWD: ${MYSQL_ROOT_PASSWORD}
      MYSQL_HOST: ${CONTAINER_MYSQL}
      MYSQL_USER: ${MYSQL_USER}
      MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD}
      DB_WAIT_RETRIES: ${DB_WAIT_RETRIES}
      DB_WAIT_SLEEP: ${DB_WAIT_SLEEP}
      DB_AUTH_NAME: ${DB_AUTH_NAME}
      DB_WORLD_NAME: ${DB_WORLD_NAME}
      DB_CHARACTERS_NAME: ${DB_CHARACTERS_NAME}
      MYSQL_CHARACTER_SET: ${MYSQL_CHARACTER_SET}
      MYSQL_COLLATION: ${MYSQL_COLLATION}
    command:
      - sh
      - -c
      - |
        # Check if databases were already restored/imported
        if [ -f "/var/lib/mysql-persistent/.restore-completed" ]; then
          echo "✅ Databases already restored from backup - init not needed"
          exit 0
        fi

        if mysql -h ${MYSQL_HOST} -u${MYSQL_USER} -p${MYSQL_ROOT_PASSWORD} -e "
          SELECT COUNT(*) FROM information_schema.tables
          WHERE table_schema IN ('${DB_AUTH_NAME}', '${DB_WORLD_NAME}', '${DB_CHARACTERS_NAME}');" -s -N 2>/dev/null | grep -q -v '^0$'; then
          echo "✅ Databases already populated - init not needed"
          exit 0
        fi

        echo "🔧 Databases need initialization - proceeding with fresh setup"

        # Install curl for downloading db init script
        microdnf install -y curl || yum install -y curl || (apt-get update && apt-get install -y curl)

        # Create fresh databases only
        echo "🗄️ Creating fresh AzerothCore databases..."
        mysql -h ${MYSQL_HOST} -u${MYSQL_USER} -p${MYSQL_ROOT_PASSWORD} -e "
        CREATE DATABASE IF NOT EXISTS ${DB_AUTH_NAME} DEFAULT CHARACTER SET ${MYSQL_CHARACTER_SET} COLLATE ${MYSQL_COLLATION};
        CREATE DATABASE IF NOT EXISTS ${DB_WORLD_NAME} DEFAULT CHARACTER SET ${MYSQL_CHARACTER_SET} COLLATE ${MYSQL_COLLATION};
        CREATE DATABASE IF NOT EXISTS ${DB_CHARACTERS_NAME} DEFAULT CHARACTER SET ${MYSQL_CHARACTER_SET} COLLATE ${MYSQL_COLLATION};
        SHOW DATABASES;" || {
          echo "❌ Failed to create databases"
          exit 1
        }

        # Set marker for import to proceed
        echo "$(date): Fresh databases created - import needed" > /var/lib/mysql-persistent/.restore-failed
        echo "✅ Fresh databases created!"
    restart: "no"

  # Step 4: Database import (one-time setup - attempts restore first)
  ac-db-import:
    image: ${AC_DB_IMPORT_IMAGE}
    container_name: ${CONTAINER_DB_IMPORT}
    user: "0:0"
    depends_on:
      ac-mysql:
        condition: service_healthy
    networks:
      - azerothcore
    volumes:
      - ${STORAGE_PATH}/config:/azerothcore/env/dist/etc
      - ${STORAGE_PATH}/logs:/azerothcore/env/dist/logs
      - ${STORAGE_PATH}/mysql-data:/var/lib/mysql-persistent
      - ./scripts/db-import-conditional.sh:/tmp/db-import-conditional.sh:ro
    environment:
      AC_DATA_DIR: "/azerothcore/data"
      AC_LOGS_DIR: "/azerothcore/logs"
      AC_LOGIN_DATABASE_INFO: "${CONTAINER_MYSQL};${MYSQL_PORT};${MYSQL_USER};${MYSQL_ROOT_PASSWORD};${DB_AUTH_NAME}"
      AC_WORLD_DATABASE_INFO: "${CONTAINER_MYSQL};${MYSQL_PORT};${MYSQL_USER};${MYSQL_ROOT_PASSWORD};${DB_WORLD_NAME}"
      AC_CHARACTER_DATABASE_INFO: "${CONTAINER_MYSQL};${MYSQL_PORT};${MYSQL_USER};${MYSQL_ROOT_PASSWORD};${DB_CHARACTERS_NAME}"
      AC_CLOSE_IDLE_CONNECTIONS: "false"
      AC_UPDATES_ENABLE_DATABASES: "7"
      AC_UPDATES_AUTO_SETUP: "1"
      # Additional environment variables for conditional import
      CONTAINER_MYSQL: ${CONTAINER_MYSQL}
      MYSQL_PORT: ${MYSQL_PORT}
      MYSQL_USER: ${MYSQL_USER}
      MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD}
      DB_AUTH_NAME: ${DB_AUTH_NAME}
      DB_WORLD_NAME: ${DB_WORLD_NAME}
      DB_CHARACTERS_NAME: ${DB_CHARACTERS_NAME}
      CONTAINER_USER: ${CONTAINER_USER}
    entrypoint:
      - sh
      - -c
      - |
        # Set ownership for config directories
        chown ${CONTAINER_USER} /azerothcore/env/dist/etc 2>/dev/null || true

        # Use local conditional db import script
        echo "📥 Using local database import script..."
        /tmp/db-import-conditional.sh
    restart: "no"

networks:
  azerothcore:
    driver: bridge
    name: ${NETWORK_NAME}
    ipam:
      config:
        - subnet: ${NETWORK_SUBNET}
          gateway: ${NETWORK_GATEWAY}