#!/usr/bin/env bash
# Switch back to the previous release (code only; migrations are additive so older code keeps working).
set -euo pipefail
# shellcheck source=/dev/null
[ -f /etc/cioclub/release.env ] && . /etc/cioclub/release.env
APP_DIR="${APP_DIR:-/var/www/cioclub}"
CUR="$(readlink -f "$APP_DIR/current")"
PREV="$(ls -1dt "$APP_DIR"/releases/*/ | sed 's#/$##' | grep -vx "$CUR" | head -n1)"
[ -n "$PREV" ] || { echo "No previous release" >&2; exit 1; }
ln -sfn "$PREV" "$APP_DIR/current.new" && mv -Tf "$APP_DIR/current.new" "$APP_DIR/current"
[ "${SKIP_RELOAD:-}" = "1" ] || systemctl reload "${FPM_SERVICE:-php8.3-fpm}"
echo "$(date -u +%FT%TZ) rolled back from $(basename "$CUR") to $(basename "$PREV")" | tee -a "$APP_DIR/shared/storage/logs/release.log"
