#!/usr/bin/env bash
#
# Deploys SIMKATMAWA to the production server (/var/www/html/simkatmawa).
#
# Run by Bitbucket Pipelines on the self-hosted Linux Shell runner installed on
# the production server itself, as user `pancasila`. The deployed commit is
# fetched straight out of the pipeline clone directory, so the server needs no
# Bitbucket credentials of its own.
#
# Nothing here needs root: `pancasila` owns the checkout and is a member of the
# `www-data` group, and storage/ + bootstrap/cache/ are group-writable setgid
# directories, so files created here stay writable for Apache.

set -euo pipefail
umask 002

APP_DIR="${APP_DIR:-/var/www/html/simkatmawa}"
PHP_BIN="${PHP_BIN:-php}"
COMPOSER_BIN="${COMPOSER_BIN:-composer}"
SOURCE_DIR="${BITBUCKET_CLONE_DIR:-$PWD}"

step() { printf '\n--- %s\n' "$1"; }

[ -d "$APP_DIR/.git" ] || { echo "ERROR: $APP_DIR is not a git checkout"; exit 1; }
[ -f "$APP_DIR/.env" ] || { echo "ERROR: $APP_DIR/.env is missing"; exit 1; }

cd "$APP_DIR"

leave_maintenance() { "$PHP_BIN" artisan up >/dev/null 2>&1 || true; }

step "Maintenance mode on"
"$PHP_BIN" artisan down --retry=15 || true
trap leave_maintenance EXIT

step "Update working tree"
git fetch --no-tags --force "$SOURCE_DIR" "HEAD:refs/remotes/pipeline/deploy"
git reset --hard FETCH_HEAD

step "Install PHP dependencies"
"$COMPOSER_BIN" install --no-dev --no-interaction --prefer-dist --optimize-autoloader

step "Run database migrations"
"$PHP_BIN" artisan migrate --force

step "Rebuild framework caches"
"$PHP_BIN" artisan optimize

step "Maintenance mode off"
trap - EXIT
"$PHP_BIN" artisan up

step "Deployed $(git rev-parse --short HEAD)"
