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

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
PHP_BIN="${PHP_BIN:-/opt/cpanel/ea-php85/root/usr/bin/php}"

if [[ ! -x "$PHP_BIN" ]]; then
    PHP_BIN="$(command -v php || true)"
fi

if [[ -z "$PHP_BIN" || ! -x "$PHP_BIN" ]]; then
    echo "ERROR: PHP CLI binary was not found." >&2
    exit 1
fi

cd "$ROOT"

mkdir -p logs storage/cache storage/sessions storage/tmp storage/uploads/private
chmod 750 logs storage/cache
chmod 700 storage/sessions storage/tmp storage/uploads/private

if [[ ! -f .env ]]; then
    cp .env.example .env
    chmod 600 .env
    echo "Created $ROOT/.env from .env.example"
else
    chmod 600 .env
    echo "Existing $ROOT/.env preserved"
fi

if grep -Eq '^APP_KEY=(""|)$' .env; then
    "$PHP_BIN" bin/console app:key --write
else
    echo "Existing non-empty APP_KEY preserved"
fi

echo
echo "Private directories and APP_KEY are prepared."
echo "Next: edit $ROOT/.env, then run:"
echo "  $PHP_BIN $ROOT/bin/console app:check"
echo "  $PHP_BIN $ROOT/bin/console db:check"
