#!/bin/bash
# Switch back to the previous release in seconds.
#   sudo greenathon-rollback
# Database migrations are NOT reversed. Only roll back past a release whose
# migrations are backwards compatible, or restore the database too.
set -Eeuo pipefail
APP=${GREENATHON_APP:-/var/www/greenathon}
APP_USER=${GREENATHON_USER:-greenathon}
FPM_SERVICE=${GREENATHON_FPM_SERVICE:-php8.3-fpm}
[[ $EUID -eq 0 ]] || { echo "Run with sudo." >&2; exit 1; }

CUR=$(readlink -f "$APP/current")
PREV=$(ls -1d "$APP"/releases/*/ | sed 's#/$##' | sort | awk -v cur="$CUR" '$0 < cur' | tail -1)
[[ -n $PREV ]] || { echo "No earlier release to roll back to." >&2; exit 1; }

echo "Rolling back: $(basename "$CUR") -> $(basename "$PREV")"
ln -sfn "$PREV" "$APP/current.new" && mv -Tf "$APP/current.new" "$APP/current"
sudo -u "$APP_USER" -H php "$APP/current/artisan" optimize
systemctl reload "$FPM_SERVICE"
sudo -u "$APP_USER" -H php "$APP/current/artisan" queue:restart
sudo -u "$APP_USER" -H php "$APP/current/artisan" up
echo "Now serving $(basename "$PREV")."
