#!/usr/bin/env sh
set -eu

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

if [ ! -L public/storage ]; then
    rm -rf public/storage
    ln -s ../storage/app/public public/storage
fi

if [ "$(id -u)" = "0" ]; then
    chown -R www-data:www-data storage bootstrap/cache
fi

if [ -z "${APP_KEY:-}" ]; then
    echo "ERROR: APP_KEY is empty. Set it in .env.production, then restart containers." >&2
    echo "  php artisan key:generate --show" >&2
    exit 1
fi

if php artisan list --raw 2>/dev/null | grep -q '^l5-swagger:generate'; then
    php artisan l5-swagger:generate --no-interaction
fi

exec "$@"
