#!/usr/bin/env bash
# Deploys BeAuthentic from a cPanel Git clone into the live app folder.
# Run by cPanel (.cpanel.yml) from the repository root; safe to re-run.
#
# Where the app lives (default ~/beauthentic). To change it, put the path in
# ~/.beauthentic-deploy-path — e.g. "/home/cpuser/public_html" when the app is
# extracted straight into public_html.
#
#   1. copies the code (never touches .env, storage/, uploads, backups, logs)
#   2. composer install --no-dev with PHP 8.3+
#   3. if the store is installed: maintenance mode → migrate → re-cache → live
#      otherwise: tells you to open /install
set -euo pipefail

REPO="$(cd "$(dirname "$0")/.." && pwd)"
DEPLOYPATH="${DEPLOYPATH:-$(cat "$HOME/.beauthentic-deploy-path" 2>/dev/null || echo "$HOME/beauthentic")}"
DEPLOYPATH="${DEPLOYPATH%/}"
say() { echo "[beauthentic deploy] $*"; }

# --- Safety: never deploy over something that isn't this app ---------------------
case "$DEPLOYPATH" in
  ""|"/"|"$HOME"|"$REPO") say "Refusing to deploy to '$DEPLOYPATH'."; exit 1;;
esac
if [ -d "$DEPLOYPATH" ] && [ ! -f "$DEPLOYPATH/artisan" ]; then
  others="$(ls -A "$DEPLOYPATH" | grep -vxE 'cgi-bin|\.well-known|error_log|\.user\.ini|php\.ini|\.htaccess|index\.html|default\.html|\.ftpquota' || true)"
  if [ -n "$others" ]; then
    say "$DEPLOYPATH already contains other files (e.g. $(echo "$others" | head -3 | tr '\n' ' '))."
    say "Use an empty folder, or put a different path in ~/.beauthentic-deploy-path. Nothing was changed."
    exit 1
  fi
fi

# --- Find PHP 8.3+ CLI and Composer ----------------------------------------------
PHP=""
for c in ${PHP_BIN:-} /opt/cpanel/ea-php84/root/usr/bin/php /opt/cpanel/ea-php83/root/usr/bin/php /usr/local/bin/php "$(command -v php || true)"; do
  if [ -n "$c" ] && [ -x "$c" ] && "$c" -r 'exit(version_compare(PHP_VERSION, "8.3.0", ">=") ? 0 : 1);' 2>/dev/null; then PHP="$c"; break; fi
done
[ -n "$PHP" ] || { say "PHP 8.3+ CLI not found. Ask your host, or set PHP_BIN in .cpanel.yml."; exit 1; }
COMPOSER=""
for c in ${COMPOSER_BIN:-} /opt/cpanel/composer/bin/composer /usr/local/bin/composer "$(command -v composer || true)" "$HOME/composer.phar"; do
  if [ -n "$c" ] && [ -f "$c" ]; then COMPOSER="$c"; break; fi
done
if [ -z "$COMPOSER" ]; then
  say "Composer not found — downloading it to ~/composer.phar"
  "$PHP" -r "copy('https://getcomposer.org/download/latest-stable/composer.phar', getenv('HOME').'/composer.phar');"
  COMPOSER="$HOME/composer.phar"
fi
say "PHP: $("$PHP" -r 'echo PHP_VERSION;') ($PHP) · deploying $(git -C "$REPO" rev-parse --short HEAD 2>/dev/null || echo '?') to $DEPLOYPATH"

INSTALLED=0
if [ -f "$DEPLOYPATH/.env" ] && [ -f "$DEPLOYPATH/vendor/autoload.php" ] && grep -qE '^APP_KEY=.+' "$DEPLOYPATH/.env"; then INSTALLED=1; fi
art() { (cd "$DEPLOYPATH" && "$PHP" artisan "$@"); }

if [ "$INSTALLED" = 1 ]; then
  say "Maintenance mode on"
  art down --render="errors::503" --retry=60 || true
  trap 'say "Bringing the store back online"; art up || true' EXIT
fi

# --- Copy code --------------------------------------------------------------------
# Only BeAuthentic's own folders are synced with --delete. Top-level files are
# copied without deleting anything, so other sites or folders living next to the
# app (e.g. addon domains inside public_html) are never touched.
mkdir -p "$DEPLOYPATH"
APP_DIRS="app bootstrap config database lang public resources routes scripts"
for d in $APP_DIRS; do
  [ -d "$REPO/$d" ] || continue
  mkdir -p "$DEPLOYPATH/$d"
  rsync -a --delete \
    --exclude '/storage' --exclude '/hot' --exclude '/cache/*.php' --exclude '*.sqlite' --exclude '*.sqlite-journal' \
    "$REPO/$d/" "$DEPLOYPATH/$d/"
done
# Root files (artisan, composer.*, .htaccess, docs…) — copy only, never delete.
rsync -a --exclude '*/' --exclude '.env' --exclude '.env.*.local' --exclude '.git' "$REPO/" "$DEPLOYPATH/"

# Storage tree (kept between deploys: uploads, logs, backups, installer state).
for d in app/public app/private/media framework/cache/data framework/sessions framework/views logs; do mkdir -p "$DEPLOYPATH/storage/$d"; done
mkdir -p "$DEPLOYPATH/bootstrap/cache"
chmod -R u+rwX "$DEPLOYPATH/storage" "$DEPLOYPATH/bootstrap/cache"

# --- Dependencies -----------------------------------------------------------------
say "Installing PHP dependencies"
(cd "$DEPLOYPATH" && "$PHP" "$COMPOSER" install --no-dev --optimize-autoloader --no-interaction --no-progress 2>&1 | tail -3)

# --- Database & caches --------------------------------------------------------------
if [ "$INSTALLED" = 1 ]; then
  say "Migrating database"
  art migrate --force
  [ -e "$DEPLOYPATH/public/storage" ] || art storage:link || say "storage:link failed — product photos need it (see DEPLOYMENT.md)"
  art optimize:clear >/dev/null
  art optimize
  say "Done ✓ — check Admin → System or run: $PHP artisan beauthentic:doctor"
else
  say "Code is in place. Finish setup in your browser: https://YOUR-DOMAIN/install"
fi
