#!/bin/sh
set -e

# Config
APP_DIR="/var/www/html"
MODULE_DIR="$APP_DIR/modules/washcertificates"
LOG_FILE="/var/log/php/composer-install.log"

# Gate auto-install (set to "true" only on one PHP container, e.g. php1)
AUTO_COMPOSER_INSTALL="${AUTO_COMPOSER_INSTALL:-true}"

log() { printf "[entrypoint] %s\n" "$*"; }

wait_for_redis() {
  host="${REDIS_CONFIG_HOST:-redis}"
  port="${REDIS_CONFIG_PORT:-6379}"
  pass="${REDIS_CONFIG_PASSWORD:-}"
  timeout="${REDIS_WAIT_TIMEOUT:-60}"
  i=0

  log "Waiting for Redis at ${host}:${port} (timeout: ${timeout}s) ..."
  while [ "$i" -lt "$timeout" ]; do
    if [ -n "$pass" ]; then
      if redis-cli -h "$host" -p "$port" -a "$pass" PING >/dev/null 2>&1; then
        log "Redis is ready"
        return 0
      fi
    else
      if redis-cli -h "$host" -p "$port" PING >/dev/null 2>&1; then
        log "Redis is ready"
        return 0
      fi
    fi
    sleep 1; i=$((i+1))
  done
  log "ERROR: Timed out waiting for Redis at ${host}:${port}"
  return 1
}

wait_for_file() {
  target="$1"; timeout="${2:-120}"; i=0
  while [ "$i" -lt "$timeout" ]; do
    if [ -e "$target" ]; then return 0; fi
    sleep 1; i=$((i+1))
  done
  return 1
}

with_install_lock() {
  # Poor-man's lock using a directory
  while ! mkdir /tmp/composer-install.lock 2>/dev/null; do
    sleep 1
  done
  trap 'rmdir /tmp/composer-install.lock 2>/dev/null || true' EXIT HUP INT TERM
  "$@"
  rmdir /tmp/composer-install.lock 2>/dev/null || true
  trap - EXIT HUP INT TERM
}

install_if_needed() {
  dir="$1"
  if [ -f "$dir/composer.json" ]; then
    if [ ! -f "$dir/vendor/autoload.php" ]; then
      log "Installing Composer deps in $dir ..."
      # Ensure log directory exists
      mkdir -p "$(dirname "$LOG_FILE")" 2>/dev/null || true
      # Run install and log output
      if ! COMPOSER_ALLOW_SUPERUSER=1 composer install \
        --no-dev --prefer-dist --optimize-autoloader --no-interaction \
        -d "$dir" 2>&1 | tee -a "$LOG_FILE"; then
        log "ERROR: composer install failed in $dir. See $LOG_FILE"
        exit 1
      fi
      # Verify autoload was created
      if [ ! -f "$dir/vendor/autoload.php" ]; then
        log "ERROR: autoload.php still missing after install in $dir. See $LOG_FILE"
        exit 1
      fi
      # Best-effort permissions fix (ignore errors on non-Linux filesystems)
      chown -R www-data:www-data "$dir/vendor" 2>/dev/null || true
    else
      log "vendor already present in $dir — skipping"
    fi
  fi
}

# Optionally perform auto-install (only on the designated container)
if [ "$AUTO_COMPOSER_INSTALL" = "true" ]; then
  # Wait for the bind mount and composer.json to appear (common on Windows/macOS)
  if ! wait_for_file "$APP_DIR/composer.json" 120; then
    log "WARNING: $APP_DIR/composer.json not found after waiting — skipping auto-install"
  else
    with_install_lock install_if_needed "$APP_DIR"
  fi

  # Module (optional)
  if [ -f "$MODULE_DIR/composer.json" ]; then
    with_install_lock install_if_needed "$MODULE_DIR"
  fi
else
  log "AUTO_COMPOSER_INSTALL=false — skipping Composer auto-install"
fi

# Wait for Redis before starting PHP-FPM (if host is defined)
if [ -n "${REDIS_CONFIG_HOST:-}" ]; then
  wait_for_redis
fi

exec "$@"
