#!/usr/bin/env bash
# ============================================================
# Funfrock CMS — Laravel deploy script (run by the server hook)
# Pre-requisites on the server (one-time):
#   - PHP 8.2+ with FPM + extensions: intl, mbstring, pdo_mysql, openssl,
#     tokenizer, xml, ctype, json, bcmath, fileinfo, curl, gd
#   - Composer
#   - MariaDB/MySQL database created + a production .env in place
#   - The web server (Nginx/Apache) DOCROOT must point to  <project>/public
#   - storage/ and bootstrap/cache/ writable by the web user
# ============================================================
set -euo pipefail
cd "$(dirname "$0")"

echo "→ Pulling latest main…"
git pull origin main

echo "→ Installing PHP deps (prod)…"
composer install --no-dev --optimize-autoloader --no-interaction --prefer-dist

echo "→ Running migrations…"
php artisan migrate --force

echo "→ Provisioning CMS pages (idempotent, non-destructive)…"
# Carries newly-added pages/blocks to prod on every deploy. The seeder never
# overwrites a page that already has blocks, so client edits are always safe.
php artisan db:seed --class=CmsPagesSeeder --force

echo "→ Linking storage…"
php artisan storage:link --force || true
if [ -e public/storage ]; then
  echo "  ✓ public/storage link OK"
else
  echo "  ⚠ WARNING: public/storage link is MISSING — uploaded images will be served by PHP (slower). Check permissions."
fi

echo "→ Caching config / routes / views…"
php artisan optimize:clear
php artisan config:cache
php artisan route:cache
php artisan view:cache

echo "✓ Deploy complete."
