FROM php:8.1-fpm

ARG JEXACTYL_VERSION=v3.7.4

# Install system dependencies
RUN apt-get update && apt-get install -y \
    curl \
    git \
    libpng-dev \
    libonig-dev \
    libxml2-dev \
    libzip-dev \
    libgd-dev \
    nginx \
    supervisor \
    unzip \
    zip \
    && rm -rf /var/lib/apt/lists/*

# Install PHP extensions
RUN docker-php-ext-install \
    bcmath \
    exif \
    gd \
    mbstring \
    pcntl \
    pdo_mysql \
    zip

# Install Redis extension
RUN pecl install redis && docker-php-ext-enable redis

# Install Composer
COPY --from=composer:2 /usr/bin/composer /usr/bin/composer

# Download and extract the Jexactyl release
RUN curl -fsSL -o /tmp/panel.tar.gz \
      "https://github.com/Jexactyl/Jexactyl/releases/download/${JEXACTYL_VERSION}/panel.tar.gz" \
    && mkdir -p /var/www/html \
    && tar -xzf /tmp/panel.tar.gz -C /var/www/html \
    && rm /tmp/panel.tar.gz

WORKDIR /var/www/html

# Install PHP dependencies (no dev, optimised autoloader)
RUN composer install --no-dev --optimize-autoloader --no-interaction

# Ensure storage and cache directories exist and are writable
RUN mkdir -p storage/logs storage/framework/{sessions,views,cache} bootstrap/cache \
    && chown -R www-data:www-data storage bootstrap/cache \
    && chmod -R 755 storage bootstrap/cache

# Nginx config
COPY nginx.conf /etc/nginx/sites-available/default

# Supervisor config (nginx + php-fpm + queue worker)
COPY supervisord.conf /etc/supervisor/conf.d/supervisord.conf

# Entrypoint: bootstrap the app on first run then hand off to supervisord
COPY entrypoint.sh /entrypoint.sh
RUN chmod +x /entrypoint.sh

EXPOSE 80

ENTRYPOINT ["/entrypoint.sh"]
