#!/bin/sh
# =============================================================================
# Container entrypoint for the EFET backend.
#
# Runs on every container start (local dev AND each Portainer redeploy):
#   1. Ensure a .env exists (server: rendered from .env.docker; dev: bind-mounted)
#   2. Install PHP deps if vendor/ is missing (dev bind-mount first boot)
#   3. Wait for the database to accept connections
#   4. Make the storage dirs writable and (re)create the public storage symlink
#   5. Run migrations when AUTO_MIGRATE=true
#   6. Clear caches
# =============================================================================
set -e

APP_DIR=/var/www/html
cd "$APP_DIR"

# 1. --- .env ---------------------------------------------------------------
# Server: no .env in the image (dockerignored) -> render from the template,
# substituting values provided by the Portainer stack environment.
# Local dev: .env is bind-mounted from the host -> left untouched.
if [ ! -f .env ]; then
    if [ -f .env.docker ]; then
        echo "[entrypoint] Rendering .env from .env.docker template..."
        envsubst < .env.docker > .env
    else
        echo "[entrypoint] No .env found, copying .env.example..."
        cp .env.example .env
    fi
fi

# 2. --- dependencies (dev first boot) --------------------------------------
if [ ! -d vendor ]; then
    echo "[entrypoint] vendor/ missing -> composer install..."
    composer install --no-interaction --prefer-dist
fi

# 3. --- wait for the database ----------------------------------------------
if [ -n "$DB_HOST" ]; then
    echo "[entrypoint] Waiting for database ${DB_HOST}:${DB_PORT:-3306}..."
    until php -r "exit(@fsockopen(getenv('DB_HOST'), intval(getenv('DB_PORT') ?: 3306)) ? 0 : 1);" 2>/dev/null; do
        sleep 2
    done
    echo "[entrypoint] Database is up."
fi

# 4. --- writable dirs + storage symlink ------------------------------------
# storage/app/public and storage/app/private are docker volumes: create them if
# the volume was empty and fix ownership before Laravel touches them.
mkdir -p storage/app/public/uploads storage/app/private \
         storage/framework/cache/data storage/framework/sessions \
         storage/framework/views storage/logs bootstrap/cache
chown -R www-data:www-data storage bootstrap/cache 2>/dev/null || true

# The symlink committed in the repo points at Lando's /app path; recreate it
# for this container path. Remove any stale/broken link first.
[ -L public/storage ] && rm -f public/storage
php artisan storage:link || true

# 5. --- migrations (opt-in) ------------------------------------------------
if [ "$AUTO_MIGRATE" = "true" ]; then
    echo "[entrypoint] Running migrations..."
    php artisan migrate --force
    php artisan migrate --path=database/migrations/project --force
fi

# 6. --- clear caches -------------------------------------------------------
# No config:cache on purpose: this app is regularly redeployed with new stack
# env values, and a stale cached config would silently win over them.
php artisan config:clear
php artisan route:clear
php artisan view:clear
php artisan cache:clear || true

exec "$@"
