#!/bin/bash
set -e

APP_DIR="/var/www/html/disposisi"
SCRIPT="/var/www/html/disposisi/deploy.sh"

if [ "$(id -u)" -ne 0 ]; then
  echo "Bukan root, menjalankan ulang sebagai root..."
  exec sudo -n /bin/bash "$SCRIPT"
fi

echo "=== Deploy started: $(date) ==="

cd "$APP_DIR"

echo "--- Pulling latest main ---"
git fetch origin main
git reset --hard origin/main

echo "--- Installing PHP dependencies ---"
composer install --no-dev --no-interaction --prefer-dist --optimize-autoloader

echo "--- Installing JS dependencies ---"
if [ -f package-lock.json ]; then
  npm ci
else
  npm install
fi

echo "--- Building assets (Vite) ---"
npm run build

echo "--- Fixing permissions ---"
chgrp -R www-data storage bootstrap/cache 2>/dev/null || true
chmod -R 775 storage bootstrap/cache 2>/dev/null || true

echo "--- Clearing & rebuilding Laravel cache ---"
php artisan optimize:clear
php artisan config:cache
php artisan route:cache
php artisan view:cache

echo "=== Deploy finished: $(date) ==="
