ARG PHP_IMAGE=php:8.2-cli
ARG COMPOSER_IMAGE=composer:2

FROM ${COMPOSER_IMAGE} AS composer

FROM ${PHP_IMAGE}

RUN apt-get update \
    && apt-get install -y --no-install-recommends \
        git \
        unzip \
        sqlite3 \
        libsqlite3-dev \
        default-mysql-client \
        libonig-dev \
        libxml2-dev \
    && docker-php-ext-install pdo_sqlite pdo_mysql mbstring xml \
    && rm -rf /var/lib/apt/lists/*

COPY --from=composer /usr/bin/composer /usr/bin/composer

ENV APP_DIR=/app
WORKDIR ${APP_DIR}

COPY . ${APP_DIR}

RUN printf '%s\n' \
  '#!/bin/sh' \
  'set -e' \
  'if [ -z "${APP_KEY:-}" ]; then' \
  '  if command -v php >/dev/null 2>&1; then' \
  '    APP_KEY=$(php -r '"'"'echo "base64:" . base64_encode(random_bytes(32));'"'"')' \
  '  elif command -v openssl >/dev/null 2>&1; then' \
  '    APP_KEY=$(openssl rand -base64 32 | sed "s/^/base64:/")' \
  '  else' \
  '    echo "APP_KEY is required but php/openssl is unavailable." >&2' \
  '    exit 1' \
  '  fi' \
  '  export APP_KEY' \
  'fi' \
  'exec "$@"' \
  > /usr/local/bin/ci-entrypoint \
  && chmod +x /usr/local/bin/ci-entrypoint

ENTRYPOINT ["ci-entrypoint"]
