#!/usr/bin/env bash
#
# Piedra Total Perú — production deploy.
#
# GOLDEN RULE: never run migrations without a fresh backup first.
# Order is fixed and enforced: backup -> migrate -> optimize.
# `set -e` aborts the whole script if the pre-migration backup fails, so a
# failed backup can never be followed by a migration.
#
# Usage (from the project root, inside the app container):
#   docker compose exec app bash scripts/deploy.sh
#
# Required production environment variables (see README "Backups y despliegue"):
#   APP_ENV=production, APP_KEY, APP_URL
#   DB_CONNECTION, DB_HOST, DB_PORT, DB_DATABASE, DB_USERNAME, DB_PASSWORD
#   CACHE_STORE, SESSION_DRIVER, QUEUE_CONNECTION, REDIS_*
#   BACKUP_NOTIFICATION_EMAIL  (optional: enables backup mail notifications)
#
# `mysqldump` must exist in the app image (it ships via default-mysql-client).

set -euo pipefail

echo "==> 0/4  Ensuring the public storage symlink (storage:link)"
php artisan storage:link || true

echo "==> 1/4  Pre-migration database backup (backup:run --only-db)"
php artisan backup:run --only-db

echo "==> 2/4  Running migrations (migrate --force)"
php artisan migrate --force

echo "==> 3/4  Optimizing caches (optimize)"
php artisan optimize

echo "Deploy complete."
