#!/bin/bash
# Filename: deploy.sh
# Run this deploy script as root to install code updates and DB migrations

# Ensure this script is run as root
if [ "$(id -u)" -ne 0 ]; then
  echo "This script must be run as root. Please use sudo."
  exit 1
fi

# Function to run commands as www-data user
run_as_www_data() {
  su -s /bin/bash www-data -c "$*"
}

# Abort script on errors
set -eoux pipefail

run_as_www_data "php artisan down --refresh=15"

git pull
composer install --no-dev

run_as_www_data "php artisan optimize:clear"
run_as_www_data "php artisan filament:optimize-clear"
run_as_www_data "php artisan migrate"
run_as_www_data "php artisan optimize"
run_as_www_data "php artisan filament:optimize"

chown -Rh www-data: bootstrap/cache storage

run_as_www_data "php artisan up"
