# ==============================================
# AZEROTHCORE SERVICES LAYER
# ==============================================
# Authentication server, world server, client data, modules, and optional services
# Deploy this layer AFTER the database layer is running

services:
  # Client Data Download Service
  ac-client-data:
    image: ${AC_CLIENT_DATA_IMAGE}
    pull_policy: ${IMAGE_PULL_POLICY}
    container_name: ${CONTAINER_CLIENT_DATA}
    user: "0:0"  # Run as root to install packages
    volumes:
      - ${STORAGE_PATH}/data:/azerothcore/data
      - ${STORAGE_PATH}/cache:/cache
    working_dir: /tmp
    environment:
      - CONTAINER_USER=${CONTAINER_USER}
    command:
      - sh
      - -c
      - |
        # Auto-detect package manager and install dependencies (as root)
        if command -v apk >/dev/null 2>&1; then
          # Alpine Linux - install full wget and bash for script compatibility
          apk add --no-cache curl unzip wget bash ca-certificates p7zip aria2 jq
        elif command -v apt-get >/dev/null 2>&1; then
          # Ubuntu/Debian
          apt-get update && apt-get install -y --no-install-recommends curl unzip wget bash ca-certificates p7zip-full aria2 jq && rm -rf /var/lib/apt/lists/*
        elif command -v yum >/dev/null 2>&1; then
          # CentOS/RHEL
          yum install -y curl unzip wget bash ca-certificates p7zip aria2 jq
        else
          echo "❌ Unsupported package manager - please install: curl unzip wget bash ca-certificates p7zip aria2 jq"
          exit 1
        fi

        # Create cache directory with correct ownership
        mkdir -p /cache
        chown ${CONTAINER_USER} /cache /azerothcore/data 2>/dev/null || true

        # Download and execute client data script from GitHub
        echo "📥 Downloading client data script from GitHub..."
        curl -fsSL https://raw.githubusercontent.com/uprightbass360/acore-compose/main/scripts/download-client-data.sh -o /tmp/download-client-data.sh
        chmod +x /tmp/download-client-data.sh
        bash /tmp/download-client-data.sh
    restart: "no"
    networks:
      - azerothcore

  # Auth server
  ac-authserver:
    image: ${AC_AUTHSERVER_IMAGE}
    pull_policy: ${IMAGE_PULL_POLICY}
    container_name: ${CONTAINER_AUTHSERVER}
    user: "${CONTAINER_USER}"  # Use mapped user for NFS compatibility
    environment:
      AC_LOGIN_DATABASE_INFO: "${CONTAINER_MYSQL};${MYSQL_PORT};${MYSQL_USER};${MYSQL_ROOT_PASSWORD};${DB_AUTH_NAME}"
      AC_UPDATES_ENABLE_DATABASES: "0"
      AC_BIND_IP: "0.0.0.0"
      AC_LOG_LEVEL: "1"
      AC_LOGGER_ROOT_CONFIG: "1,Console"
      AC_LOGGER_SERVER_CONFIG: "1,Console"
      AC_APPENDER_CONSOLE_CONFIG: "1,2,0"
    ports:
      - "${AUTH_EXTERNAL_PORT}:${AUTH_PORT}"
    restart: unless-stopped
    networks:
      - azerothcore
    volumes:
      - ${STORAGE_PATH}/config:/azerothcore/env/dist/etc
    cap_add:
      - SYS_NICE
    healthcheck:
      test: ["CMD", "sh", "-c", "ps aux | grep '[a]uthserver' | grep -v grep || exit 1"]
      interval: ${AUTH_HEALTHCHECK_INTERVAL}
      timeout: ${AUTH_HEALTHCHECK_TIMEOUT}
      retries: ${AUTH_HEALTHCHECK_RETRIES}
      start_period: ${AUTH_HEALTHCHECK_START_PERIOD}

  # World server with Playerbots support
  ac-worldserver:
    image: ${AC_WORLDSERVER_IMAGE}
    pull_policy: ${IMAGE_PULL_POLICY}
    container_name: ${CONTAINER_WORLDSERVER}
    user: "${CONTAINER_USER}"  # Use mapped user for NFS compatibility
    stdin_open: true
    tty: true
    depends_on:
      - ac-authserver
      - ac-client-data
    environment:
      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_UPDATES_ENABLE_DATABASES: "0"
      AC_BIND_IP: "0.0.0.0"
      AC_DATA_DIR: "/azerothcore/data"
      AC_SOAP_PORT: "7878"
      AC_PROCESS_PRIORITY: "0"
      PLAYERBOT_ENABLED: "${PLAYERBOT_ENABLED}"
      PLAYERBOT_MAX_BOTS: "${PLAYERBOT_MAX_BOTS}"
      # Logger configuration - Use config file defaults with proper log level
      AC_LOG_LEVEL: "2"
    ports:
      - "${WORLD_EXTERNAL_PORT}:${WORLD_PORT}"
      - "${SOAP_EXTERNAL_PORT}:${SOAP_PORT}"
    volumes:
      - ${STORAGE_PATH}/data:/azerothcore/data
      - ${STORAGE_PATH}/config:/azerothcore/env/dist/etc
      - ${STORAGE_PATH}/logs:/azerothcore/logs
      - ${STORAGE_PATH}/modules:/azerothcore/modules
      - ${STORAGE_PATH}/lua_scripts:/azerothcore/lua_scripts
    restart: unless-stopped
    networks:
      - azerothcore
    cap_add:
      - SYS_NICE
    healthcheck:
      test: ["CMD", "sh", "-c", "ps aux | grep '[w]orldserver' | grep -v grep || exit 1"]
      interval: ${WORLD_HEALTHCHECK_INTERVAL}
      timeout: ${WORLD_HEALTHCHECK_TIMEOUT}
      retries: ${WORLD_HEALTHCHECK_RETRIES}
      start_period: ${WORLD_HEALTHCHECK_START_PERIOD}

  # Optional: Eluna Lua Engine
  ac-eluna:
    image: ${AC_ELUNA_IMAGE}
    pull_policy: ${IMAGE_PULL_POLICY}
    container_name: ${CONTAINER_ELUNA}
    user: "0:0"  # Run as root to handle NFS permissions
    command: npm run dev
    volumes:
      # TypeScript source files (input)
      - ${STORAGE_PATH}/typescript:/eluna-ts/src
      # Compiled Lua scripts (output)
      - ${STORAGE_PATH}/lua_scripts:/eluna-ts/dist
    environment:
      - ELUNATS_BUILD_FILE=${ELUNATS_BUILD_FILE:-index.ts}
    restart: unless-stopped
    networks:
      - azerothcore

  # Module Management Service
  ac-modules:
    image: ${ALPINE_GIT_IMAGE}
    pull_policy: ${IMAGE_PULL_POLICY}
    container_name: ${CONTAINER_MODULES}
    user: "0:0"  # Run as root to handle NFS permissions
    volumes:
      - ${STORAGE_PATH}/modules:/modules
      - ${STORAGE_PATH}/config:/azerothcore/env/dist/etc
    environment:
      - GIT_EMAIL=${GIT_EMAIL}
      - GIT_PAT=${GIT_PAT}
      - GIT_USERNAME=${GIT_USERNAME}
      - MODULE_PLAYERBOTS=${MODULE_PLAYERBOTS}
      - MODULE_AOE_LOOT=${MODULE_AOE_LOOT}
      - MODULE_LEARN_SPELLS=${MODULE_LEARN_SPELLS}
      - MODULE_FIREWORKS=${MODULE_FIREWORKS}
      - MODULE_INDIVIDUAL_PROGRESSION=${MODULE_INDIVIDUAL_PROGRESSION}
      # Quality of Life Modules
      - MODULE_AHBOT=${MODULE_AHBOT}
      - MODULE_AUTOBALANCE=${MODULE_AUTOBALANCE}
      - MODULE_TRANSMOG=${MODULE_TRANSMOG}
      - MODULE_NPC_BUFFER=${MODULE_NPC_BUFFER}
      # Gameplay Enhancement Modules
      - MODULE_DYNAMIC_XP=${MODULE_DYNAMIC_XP}
      - MODULE_SOLO_LFG=${MODULE_SOLO_LFG}
      - MODULE_1V1_ARENA=${MODULE_1V1_ARENA}
      - MODULE_PHASED_DUELS=${MODULE_PHASED_DUELS}
      # Server Management Modules
      - MODULE_BREAKING_NEWS=${MODULE_BREAKING_NEWS}
      - MODULE_BOSS_ANNOUNCER=${MODULE_BOSS_ANNOUNCER}
      - MODULE_ACCOUNT_ACHIEVEMENTS=${MODULE_ACCOUNT_ACHIEVEMENTS}
      # Additional Modules Found in Config
      - MODULE_AUTO_REVIVE=${MODULE_AUTO_REVIVE}
      - MODULE_GAIN_HONOR_GUARD=${MODULE_GAIN_HONOR_GUARD}
      - MODULE_ELUNA=${MODULE_ELUNA}
      - MODULE_TIME_IS_TIME=${MODULE_TIME_IS_TIME}
      - MODULE_POCKET_PORTAL=${MODULE_POCKET_PORTAL}
      - MODULE_RANDOM_ENCHANTS=${MODULE_RANDOM_ENCHANTS}
      - MODULE_SOLOCRAFT=${MODULE_SOLOCRAFT}
      - MODULE_PVP_TITLES=${MODULE_PVP_TITLES}
      - MODULE_NPC_BEASTMASTER=${MODULE_NPC_BEASTMASTER}
      - MODULE_NPC_ENCHANTER=${MODULE_NPC_ENCHANTER}
      - MODULE_INSTANCE_RESET=${MODULE_INSTANCE_RESET}
      - MODULE_LEVEL_GRANT=${MODULE_LEVEL_GRANT}
      - MODULE_ARAC=${MODULE_ARAC}
      - MODULE_ASSISTANT=${MODULE_ASSISTANT}
      - MODULE_REAGENT_BANK=${MODULE_REAGENT_BANK}
      - MODULE_BLACK_MARKET_AUCTION_HOUSE=${MODULE_BLACK_MARKET_AUCTION_HOUSE}
      # Database connection for SQL execution
      - CONTAINER_MYSQL=${CONTAINER_MYSQL}
      - 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: ["/bin/sh", "-c"]
    command:
      - |
        # Install packages as root
        apk add --no-cache curl bash

        # Set ownership for module directories
        mkdir -p /scripts
        chown ${CONTAINER_USER} /modules /azerothcore/env/dist/etc 2>/dev/null || true

        echo "📥 Downloading module management script from GitHub..."
        curl -fsSL https://raw.githubusercontent.com/uprightbass360/acore-compose/main/scripts/manage-modules.sh -o /tmp/manage-modules.sh
        curl -fsSL https://raw.githubusercontent.com/uprightbass360/acore-compose/main/scripts/manage-modules-sql.sh -o /scripts/manage-modules-sql.sh
        chmod +x /tmp/manage-modules.sh /scripts/manage-modules-sql.sh

        bash /tmp/manage-modules.sh
    restart: "no"
    networks:
      - azerothcore

  # Auto Post-Install Configuration Service
  ac-post-install:
    image: ${ALPINE_IMAGE}
    pull_policy: ${IMAGE_PULL_POLICY}
    container_name: ${CONTAINER_POST_INSTALL}
    user: "0:0"  # Run as root for full permissions
    volumes:
      - ${STORAGE_PATH}/config:/azerothcore/config
      - ${STORAGE_PATH}/install-markers:/install-markers
      - .:/project
      - /var/run/docker.sock:/var/run/docker.sock:rw
    working_dir: /project
    environment:
      MYSQL_HOST: ${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}
      STORAGE_PATH: ${STORAGE_PATH}
      SERVER_ADDRESS: ${SERVER_ADDRESS}
      REALM_PORT: ${REALM_PORT}
      NETWORK_NAME: ${NETWORK_NAME}
      CONTAINER_AUTHSERVER: ${CONTAINER_AUTHSERVER}
      CONTAINER_WORLDSERVER: ${CONTAINER_WORLDSERVER}
      CONTAINER_USER: ${CONTAINER_USER}
    depends_on:
      - ac-modules
    command:
      - sh
      - -c
      - |
        # Install required packages as root
        echo "📦 Installing required packages..."
        apk add --no-cache bash curl docker-cli

        # Set ownership for config directories
        chown ${CONTAINER_USER} /azerothcore/config /install-markers 2>/dev/null || true

        # Download post-install script from GitHub (fallback to local for testing)
        echo "📥 Downloading auto post-install script..."
        curl -fsSL https://raw.githubusercontent.com/uprightbass360/acore-compose/main/scripts/auto-post-install.sh -o /tmp/auto-post-install.sh
        chmod +x /tmp/auto-post-install.sh
        echo "🚀 Executing script with bash..."
        bash /tmp/auto-post-install.sh
    restart: "no"
    networks:
      - azerothcore

networks:
  azerothcore:
    external: true
    name: ${NETWORK_NAME}