#!/usr/bin/env bash

set -euo pipefail

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$ROOT_DIR"

if [ ! -f .env ]; then
    if [ -f .env.production.example ]; then
        cp .env.production.example .env
        echo 'Created .env from .env.production.example. Review and replace placeholder values before deploying.'
    else
        echo 'Missing .env and .env.production.example.'
        exit 1
    fi
fi

composer install --no-dev --prefer-dist --optimize-autoloader --no-interaction
php artisan down --render='errors::503' --retry=60 || true
php artisan migrate --force
php artisan optimize:clear
php artisan config:cache
php artisan route:cache
php artisan view:cache
php artisan event:cache

if [ -f package.json ]; then
    npm ci --no-audit --no-fund
    npm run build
fi

php artisan up
