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

# Helper for cPanel installs where DocumentRoot cannot be set to /public.
# Usage: run from the project root (the folder that contains artisan/).

PROJECT_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"

PUBLIC_DIR="${PROJECT_ROOT}/public"
ROOT_INDEX="${PROJECT_ROOT}/index.php"

if [[ ! -d "${PUBLIC_DIR}" ]]; then
  echo "ERROR: public/ folder not found at ${PUBLIC_DIR}"
  exit 1
fi

echo "Fixing document root by copying public assets to project root..."

if [[ -f "${PUBLIC_DIR}/.htaccess" ]]; then
  cp -f "${PUBLIC_DIR}/.htaccess" "${PROJECT_ROOT}/.htaccess"
  echo "Copied .htaccess to project root."
fi

# Create root index.php compatible with Laravel bootstrapping from project root.
cat > "${ROOT_INDEX}" <<'PHP'
<?php

use Illuminate\Foundation\Application;
use Illuminate\Http\Request;

define('LARAVEL_START', microtime(true));

// Determine if the application is in maintenance mode...
if (file_exists($maintenance = __DIR__.'/storage/framework/maintenance.php')) {
    require $maintenance;
}

// Register the Composer autoloader...
require __DIR__.'/vendor/autoload.php';

// Bootstrap Laravel and handle the request...
/** @var Application $app */
$app = require_once __DIR__.'/bootstrap/app.php';
$app->handleRequest(Request::capture());
PHP

echo "Generated root index.php."

# Copy the remaining public files (favicon, robots, and build output if present).
# NOTE: storage symlinks are special in Laravel. Keep using `php artisan storage:link`
# and ensure your document root can serve the created `public/storage` (or adjust accordingly).
if [[ -d "${PUBLIC_DIR}/build" ]]; then
  mkdir -p "${PROJECT_ROOT}/build"
  rsync -a --delete "${PUBLIC_DIR}/build/" "${PROJECT_ROOT}/build/"
fi

for f in "${PUBLIC_DIR}/favicon.ico" "${PUBLIC_DIR}/robots.txt"; do
  if [[ -f "$f" ]]; then
    cp -f "$f" "${PROJECT_ROOT}/$(basename "$f")"
  fi
done

echo "Done."
echo "Next: deploy assets and ensure storage symlink/paths work (run `php artisan storage:link`)."

