#!/usr/bin/env bash
set -euo pipefail

cd /var/www/html

run_as_app_user() {
    su -s /bin/bash "${APP_USER:-laravel}" -c "$*"
}

if [ ! -f .env ] && [ -f .env.example ]; then
    cp .env.example .env
fi

mkdir -p \
    bootstrap/cache \
    storage/app/public \
    storage/framework/cache/data \
    storage/framework/sessions \
    storage/framework/testing \
    storage/framework/views \
    storage/logs

chown -R "${APP_USER:-laravel}:${APP_GROUP:-laravel}" \
    bootstrap/cache \
    storage \
    vendor \
    "${COMPOSER_CACHE_DIR:-/tmp/composer-cache}" 2>/dev/null || true

run_as_app_user "git config --global --add safe.directory /var/www/html" 2>/dev/null || true

if [ ! -d vendor ] || [ -z "$(ls -A vendor 2>/dev/null)" ]; then
    run_as_app_user "composer install --no-interaction --prefer-dist"
fi

if [ -f artisan ] && ! grep -q '^APP_KEY=base64:' .env 2>/dev/null; then
    run_as_app_user "php artisan key:generate --force --no-interaction"
fi

if [ "${DB_CONNECTION:-}" = "mysql" ]; then
    until mysqladmin ping -h"${DB_HOST:-mysql}" -P"${DB_PORT:-3306}" --silent; do
        sleep 1
    done
fi

run_as_app_user "php artisan config:clear --no-interaction" >/dev/null 2>&1 || true
run_as_app_user "php artisan route:clear --no-interaction" >/dev/null 2>&1 || true
run_as_app_user "php artisan view:clear --no-interaction" >/dev/null 2>&1 || true

exec "$@"
