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

APP_DIR="${1:-/var/www/html/ngbvd}"
PATCH_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
STAMP="$(date +%Y%m%d_%H%M%S)"
BACKUP_DIR="/var/backups/ngbvd/analysis_fix_${STAMP}"
PHP_WEB_USER="${PHP_WEB_USER:-www-data}"
APP_OWNER="${APP_OWNER:-ngbvd}"

if [[ ! -d "$APP_DIR/app" || ! -f "$APP_DIR/artisan" ]]; then
  echo "ERROR: Laravel application not found at $APP_DIR" >&2
  exit 1
fi

mkdir -p "$BACKUP_DIR"

FILES=(
  "config/app.php"
  "app/Http/Controllers/AnalysisController.php"
  "app/Services/AccessControl/PermissionRegistry.php"
  "resources/views/layouts/app.blade.php"
  "resources/views/analysis/standard_workbench.blade.php"
  "resources/views/analysis/index.blade.php"
  "resources/views/analysis/mine.blade.php"
  "resources/views/analysis/region.blade.php"
  "public/assets/js/ngbvd-report-workbench.js"
)

for rel in "${FILES[@]}"; do
  if [[ -f "$APP_DIR/$rel" ]]; then
    mkdir -p "$BACKUP_DIR/$(dirname "$rel")"
    cp -a "$APP_DIR/$rel" "$BACKUP_DIR/$rel"
  fi
  mkdir -p "$APP_DIR/$(dirname "$rel")"
  cp -a "$PATCH_DIR/$rel" "$APP_DIR/$rel"
done

# Autoloaded backup controllers can cause PSR-4 duplicate-class warnings.
if [[ -f "$APP_DIR/app/Http/Controllers/AnalysisControllerv1.php" ]]; then
  mkdir -p "$BACKUP_DIR/legacy"
  mv "$APP_DIR/app/Http/Controllers/AnalysisControllerv1.php" "$BACKUP_DIR/legacy/"
fi

# These caches currently contain Barryvdh Debugbar references and prevent Artisan boot.
rm -f "$APP_DIR/bootstrap/cache/config.php" \
      "$APP_DIR/bootstrap/cache/packages.php" \
      "$APP_DIR/bootstrap/cache/services.php"

# Repair Laravel writable directories without chmod 777.
chown -R "$APP_OWNER:$PHP_WEB_USER" "$APP_DIR/storage" "$APP_DIR/bootstrap/cache"
find "$APP_DIR/storage" "$APP_DIR/bootstrap/cache" -type d -exec chmod 2775 {} \;
find "$APP_DIR/storage" "$APP_DIR/bootstrap/cache" -type f -exec chmod 664 {} \;

cd "$APP_DIR"

php -l app/Http/Controllers/AnalysisController.php
php -l app/Services/AccessControl/PermissionRegistry.php
php -l config/app.php

php artisan --version
php artisan package:discover --ansi
php artisan view:clear
php artisan config:clear
php artisan route:clear
php artisan cache:clear

# Keep views uncached while validating the report fix.
php artisan config:cache
php artisan route:cache

echo
echo "Patch deployed successfully."
echo "Backup: $BACKUP_DIR"
echo "Next: restart the active PHP-FPM service, sign in again, and test /analysis/."
