#!/bin/bash
set -e

cd /var/www/html

# Run build tooling as www-data (remapped to the host UID) so bind-mounted
# files such as vendor/ and node_modules/ stay owned by the WSL user.
export COMPOSER_HOME=/tmp/composer
export npm_config_cache=/tmp/npm
mkdir -p "$COMPOSER_HOME" "$npm_config_cache"
chown -R www-data:www-data "$COMPOSER_HOME" "$npm_config_cache"

as_web() { runuser -u www-data -- env HOME=/tmp "$@"; }

# .env is the single source of truth for application config; compose
# deliberately does not inject app variables into the container environment,
# because Laravel's immutable Dotenv will not override an already-set variable.
if [ ! -f .env ]; then
    echo "[trace] .env missing, copying from .env.docker"
    cp .env.docker .env
    chown www-data:www-data .env
fi

# Read a value out of .env, stripping quotes and CRs.
env_val() {
    sed -n "s/^[[:space:]]*$1[[:space:]]*=[[:space:]]*//p" .env \
        | tail -n 1 | tr -d '\r' | sed -e 's/^"\(.*\)"$/\1/' -e "s/^'\(.*\)'\$/\1/"
}

DB_HOST=$(env_val DB_HOST);         : "${DB_HOST:=db}"
DB_PORT=$(env_val DB_PORT);         : "${DB_PORT:=3306}"
DB_DATABASE=$(env_val DB_DATABASE); : "${DB_DATABASE:=logbook}"
DB_USERNAME=$(env_val DB_USERNAME); : "${DB_USERNAME:=logbook}"
DB_PASSWORD=$(env_val DB_PASSWORD); : "${DB_PASSWORD:=secret}"

# Probe with PDO rather than the bundled mysqladmin: Debian ships MariaDB's
# client, which refuses MySQL 8's self-signed TLS cert. PDO is also the exact
# path the application uses.
db_ready() {
    php -r '
        try { new PDO(sprintf("mysql:host=%s;port=%s;dbname=%s", $argv[1], $argv[2], $argv[3]), $argv[4], $argv[5]); }
        catch (Throwable $e) { exit(1); }
    ' "$DB_HOST" "$DB_PORT" "$DB_DATABASE" "$DB_USERNAME" "$DB_PASSWORD" >/dev/null 2>&1
}

echo "[trace] waiting for database at ${DB_HOST}:${DB_PORT} ..."
for i in $(seq 1 60); do
    if db_ready; then
        echo "[trace] database is up."
        break
    fi
    [ "$i" = 60 ] && echo "[trace] WARNING: database not reachable, continuing anyway."
    sleep 2
done

mkdir -p storage/framework/cache/data storage/framework/sessions storage/framework/views storage/logs bootstrap/cache
chown -R www-data:www-data storage bootstrap/cache
chmod -R ug+rw storage bootstrap/cache

if [ ! -f vendor/autoload.php ]; then
    echo "[trace] installing composer dependencies ..."
    as_web composer install --no-interaction --prefer-dist --optimize-autoloader
fi

if ! grep -q '^APP_KEY=base64:' .env; then
    echo "[trace] generating application key ..."
    as_web php artisan key:generate --force
fi

if [ ! -d public/build ]; then
    echo "[trace] building frontend assets (vite) — first run takes a minute ..."
    if [ ! -d node_modules ]; then
        # npm ci keeps package-lock.json untouched (npm install would rewrite
        # its "name" field, since package.json declares none).
        if [ -f package-lock.json ]; then
            as_web npm ci --no-audit --no-fund
        else
            as_web npm install --no-audit --no-fund
        fi
    fi
    as_web npm run build
fi

[ -e public/storage ] || as_web php artisan storage:link || true

as_web php artisan config:clear >/dev/null 2>&1 || true
as_web php artisan view:clear   >/dev/null 2>&1 || true

echo "[trace] ready -> http://localhost:${APP_PORT:-8000}"
exec "$@"
