#!/bin/sh
set -e
# This script assumes it is run from the app project root
#
# Usage: sh deploy.sh [--envoyer]
#
# Options:
#   --envoyer  Skip steps handled by Envoyer (composer install, cron setup)

ENVOYER=false

for arg in "$@"; do
    case "$arg" in
        --envoyer) ENVOYER=true ;;
    esac
done

echo "----------------------------------------"
echo "Clearing app caches..."

php artisan cache:clear
php artisan view:clear
php artisan twig:clear

echo "----------------------------------------"
# Install PHP dependencies if composer.json is present
if [ "$ENVOYER" = true ]; then
    echo "Skipping Composer install (handled by Envoyer)."
elif [ -f composer.json ]; then
    echo "Installing PHP dependencies..."
    composer install --no-interaction --no-dev --prefer-dist --optimize-autoloader
else
    echo "composer.json not found in $(pwd) — skipping Composer install."
fi

echo "----------------------------------------"
echo "Running migrations..."
php artisan migrate --force

echo "----------------------------------------"
echo "Publishing media manager assets..."
php artisan vendor:publish --tag=media-manager

echo "----------------------------------------"
# Setup cron jobs
if [ "$ENVOYER" = true ]; then
    echo "Skipping cron setup (handled by Envoyer)."
elif [ -f crons.sh ]; then
    echo "Installing cron jobs..."
    sh crons.sh | crontab -
else
    echo "crons.sh not found — skipping cron install."
fi

echo "----------------------------------------"
echo "Compiling frontend assets..."
npm install && npm run build

echo "----------------------------------------"
echo "Caching config and routes..."

php artisan config:cache
php artisan route:cache

echo "----------------------------------------"
echo "Deployment complete."
echo "----------------------------------------"
