#!/bin/sh
set -e

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

chown -R www-data:www-data /run/php /app/storage /app/bootstrap/cache
chmod -R ug+rwx /app/storage /app/bootstrap/cache

if [ "${DB_CONNECTION:-}" = "mysql" ] && [ -n "${DB_HOST:-}" ]; then
    echo "Waiting for MySQL at ${DB_HOST}:${DB_PORT:-3306}..."
    php -r '
        $host = getenv("DB_HOST");
        $port = getenv("DB_PORT") ?: "3306";
        $user = getenv("DB_USERNAME") ?: "root";
        $pass = getenv("DB_PASSWORD") ?: "";
        for ($i = 0; $i < 60; $i++) {
            try {
                new PDO("mysql:host={$host};port={$port}", $user, $pass);
                exit(0);
            } catch (Throwable $e) {
                sleep(1);
            }
        }
        fwrite(STDERR, "MySQL was not ready after 60s\n");
        exit(1);
    '
fi

php artisan storage:link --force >/dev/null 2>&1 || true

if [ "${RUN_MIGRATIONS:-false}" = "true" ]; then
    php artisan migrate --force
fi

if [ "${CACHE_CONFIG:-false}" = "true" ]; then
    php artisan config:cache
    php artisan route:cache
    php artisan view:cache
fi

exec "$@"
