#!/bin/sh
set -eu

if ! command -v apache2ctl >/dev/null 2>&1 || ! command -v apache2-foreground >/dev/null 2>&1; then
  echo "[start] Production runtime Apache bekliyor. Yerelde ./scripts/start-php-api.sh kullanın." >&2
  exit 1
fi

APACHE_PORT="${PORT:-8080}"
DOCROOT="${FAUNAMIX_APACHE_DOCUMENT_ROOT:-/app}"

if command -v a2dismod >/dev/null 2>&1; then
  a2dismod mpm_event mpm_worker >/dev/null 2>&1 || true
fi
if command -v a2enmod >/dev/null 2>&1; then
  a2enmod mpm_prefork >/dev/null 2>&1 || true
fi

if [ -f /etc/apache2/ports.conf ]; then
  sed -ri "s/^Listen [0-9]+$/Listen ${APACHE_PORT}/" /etc/apache2/ports.conf
fi

if [ -f /etc/apache2/sites-available/000-default.conf ]; then
  sed -ri "s#<VirtualHost \\*:[0-9]+>#<VirtualHost *:${APACHE_PORT}>#" /etc/apache2/sites-available/000-default.conf
  sed -ri "s#DocumentRoot .*#DocumentRoot ${DOCROOT}#" /etc/apache2/sites-available/000-default.conf
fi

if [ -f /etc/apache2/apache2.conf ]; then
  sed -ri "s#<Directory /var/www/>#<Directory ${DOCROOT}/>#" /etc/apache2/apache2.conf
fi

/app/api/scripts/prod-bootstrap.sh

# Railway volume: mount /app/api/uploads genelde root sahipli gelir; panel yüklemesi www-data yazmalı.
if [ -d /app/api/uploads ]; then
  chown -R www-data:www-data /app/api/uploads 2>/dev/null || true
  chmod 775 /app/api/uploads 2>/dev/null || true
fi

apache2ctl -t
exec apache2-foreground
