#!/usr/bin/env bash
set -Eeuo pipefail
unset GIT_DIR GIT_WORK_TREE GIT_INDEX_FILE
BASE=/home6/kdhccoke
APP="$BASE/public_html"
REPO="$BASE/repositories/kdhc.git"
PHP=/usr/local/bin/php
COMPOSER="$BASE/bin/composer.phar"
exec 9>"$BASE/repositories/kdhc-deploy.lock"
flock -n 9 || { echo 'Another deployment is running'; exit 1; }
cd "$APP"
TARGET="${1:-$(git --git-dir="$REPO" rev-parse refs/heads/main)}"
git fetch "$REPO" main
git merge-base --is-ancestor HEAD "$TARGET" || { echo 'Deployment must fast-forward'; exit 1; }
BACKUP="$BASE/deployment-backups/$(date -u +%Y%m%dT%H%M%SZ)"
mkdir -p "$BACKUP"
chmod 700 "$BACKUP"
git rev-parse HEAD > "$BACKUP/commit"
# Git retains immutable code history; bundle it without re-archiving large assets.
git bundle create "$BACKUP/repository.bundle" HEAD
cp .env "$BACKUP/.env"
chmod 600 "$BACKUP/.env"
git diff > "$BACKUP/uncommitted.patch"
# Generated test cache is not production content.
git restore -- .phpunit.cache/test-results 2>/dev/null || true
git merge --ff-only "$TARGET"
"$PHP" -d allow_url_fopen=1 "$COMPOSER" install --no-dev --prefer-dist --no-interaction --no-progress
"$PHP" artisan config:cache
"$PHP" artisan view:cache
"$PHP" artisan queue:restart
for path in / /about /program /partners /registrations; do
    curl --fail --silent --show-error --max-time 30 "https://kdhc.co.ke$path" -o /dev/null
done
echo "Deployment verified: $(git rev-parse --short HEAD). Backup: $BACKUP"
