#!/usr/bin/env bash
#
# Deploy the latest code on a server (dev.stimber.co.uk and later production).
#
#   cd ~/southgate_timber && ./deploy.sh            # pull main and update
#   ./deploy.sh --no-maintenance                    # keep the site up during the update
#   BRANCH=some-branch ./deploy.sh                  # deploy another branch
#
# Run as the cPanel account that owns the site (devstimberco), never as root.
# Needs: git access to GitHub (deploy key), .env already in place (never in git).

set -euo pipefail

APP_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
BRANCH="${BRANCH:-main}"
MAINTENANCE=1
[[ "${1:-}" == "--no-maintenance" ]] && MAINTENANCE=0

# PHP 8.2 from cPanel (8.3 on this server lacks fileinfo); override with PHP=/path/to/php
if [[ -z "${PHP:-}" ]]; then
    if [[ -x /opt/cpanel/ea-php82/root/usr/bin/php ]]; then PHP=/opt/cpanel/ea-php82/root/usr/bin/php; else PHP="$(command -v php)"; fi
fi
COMPOSER="${COMPOSER_BIN:-$HOME/bin/composer}"
[[ -f "$COMPOSER" ]] || COMPOSER="$(command -v composer || true)"

say() { printf '\n\033[1;32m==>\033[0m %s\n' "$*"; }
fail() { printf '\n\033[1;31mDeploy failed:\033[0m %s\n' "$*" >&2; exit 1; }

[[ "$(id -u)" -eq 0 ]] && fail "do not run as root; run as the site's cPanel user (e.g. su - devstimberco)."
cd "$APP_DIR"
[[ -f .env ]] || fail ".env is missing in $APP_DIR."
[[ -n "$COMPOSER" ]] || fail "composer not found (expected $HOME/bin/composer)."

# Hand edits on the server would be lost or block the pull: stop instead.
if [[ -n "$(git status --porcelain --untracked-files=no)" ]]; then
    git status --short --untracked-files=no
    fail "the server copy has local changes (above). Commit them from a PC or undo them first."
fi

artisan() { "$PHP" artisan "$@"; }

site_up() {
    if [[ "$MAINTENANCE" -eq 1 ]]; then artisan up >/dev/null 2>&1 || true; fi
}
trap site_up EXIT   # the site always comes back, even when a step fails

BEFORE="$(git rev-parse HEAD)"
LOCK_BEFORE="$(git rev-parse HEAD:composer.lock 2>/dev/null || echo none)"

say "Fetching $BRANCH"
git fetch --quiet origin "$BRANCH"
git checkout --quiet "$BRANCH"
if [[ "$(git rev-parse HEAD)" == "$(git rev-parse "origin/$BRANCH")" ]]; then
    echo "Already up to date at $(git log --oneline -1)."
fi

if [[ "$MAINTENANCE" -eq 1 ]]; then
    say "Maintenance mode on"
    artisan down --retry=30 >/dev/null || true
fi

say "Updating code"
git merge --ff-only --quiet "origin/$BRANCH" || fail "cannot fast-forward to origin/$BRANCH (history differs); sort it out by hand."
git log --oneline "$BEFORE..HEAD" | head -20 || true

if [[ "$(git rev-parse HEAD:composer.lock 2>/dev/null || echo none)" != "$LOCK_BEFORE" || ! -d vendor ]]; then
    say "Installing PHP packages (composer.lock changed)"
    "$PHP" -d allow_url_fopen=1 -d memory_limit=1G "$COMPOSER" install --no-dev --optimize-autoloader --no-interaction --no-progress
else
    say "PHP packages unchanged"
fi

say "Database migrations"
artisan migrate --force

say "Caches"
[[ -e public/storage ]] || artisan storage:link
artisan optimize:clear >/dev/null
artisan optimize
artisan queue:restart >/dev/null 2>&1 || true

if [[ "$MAINTENANCE" -eq 1 ]]; then
    say "Maintenance mode off"
    artisan up
fi

say "Deployed $(git log --oneline -1)"
