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

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
if ! command -v composer >/dev/null 2>&1; then
  echo "Composer is required: https://getcomposer.org/download/" >&2
  exit 1
fi
if ! command -v php >/dev/null 2>&1; then
  echo "PHP CLI is required." >&2
  exit 1
fi
if [[ -f "$ROOT/artisan" && -f "$ROOT/composer.json" ]]; then
  cd "$ROOT"
  composer install --no-interaction --prefer-dist
  if [[ ! -f .env ]]; then
    cp .env.example .env
    php artisan key:generate
  fi
  mkdir -p database
  if [[ ! -f database/database.sqlite ]]; then
    touch database/database.sqlite
  fi
  echo "Existing Laravel application prepared."
  exit 0
fi
if [[ -e "$ROOT/artisan" || -e "$ROOT/composer.json" ]]; then
  echo "Laravel is already present. Refusing to overwrite application files."
  exit 1
fi

TMP="$(mktemp -d)"
trap 'rm -rf "$TMP"' EXIT
composer create-project laravel/laravel "$TMP/laravel" --no-interaction

# Never copy scaffold's generated local .env into the repository.
rm -f "$TMP/laravel/.env"
# Preserve existing project files, including HMS routes, views, migrations and git metadata.
cp -a -n "$TMP/laravel/." "$ROOT/"
cd "$ROOT"
cp .env.example .env
php artisan key:generate

echo
echo "Laravel scaffold installed."
echo "1. Set your MySQL credentials in .env."
echo "2. Run: php artisan migrate"
echo "3. Run: php artisan serve"
echo "4. Review git status before committing generated files."
