#!/usr/bin/env bash
# Update RSPC from a newly unpacked archive (run the script FROM the new archive):
#
#   tar xzf rspc-<version>-linux-amd64.tar.gz && cd rspc-<version>
#   sudo ./scripts/update.sh [--yes]
#
# A backup of the binary, config and database is made first; if the new version
# does not start, everything is rolled back automatically.
source "$(dirname "${BASH_SOURCE[0]}")/lib.sh"

require_root
require_ubuntu
require_installed

YES=0
[[ ${1:-} == "--yes" || ${RSPC_YES:-0} == 1 ]] && YES=1

[[ "$SRC_DIR" != "$RSPC_HOME" ]] || die "run update.sh from the NEW unpacked archive, not from $RSPC_HOME"
verify_checksums

OLD_VERSION=$(installed_version)
NEW_VERSION=$(cat "$SRC_DIR/VERSION")
echo "${C_BOLD}RSPC update: $OLD_VERSION → $NEW_VERSION${C_RESET}"
if [[ $OLD_VERSION == "$NEW_VERSION" ]]; then
  warn "version $NEW_VERSION is already installed"
  ((YES)) || confirm "Reinstall the same version?" || exit 0
else
  ((YES)) || confirm "Continue?" || exit 0
fi

# --- backup ---
TS=$(date +%Y%m%d-%H%M%S)
BK="$RSPC_BACKUPS/$TS-$OLD_VERSION"
install -d -m 0750 -o "$RSPC_USER" -g "$RSPC_USER" "$BK"

info "stopping service"
systemctl stop "$RSPC_SERVICE"

info "backing up to $BK"
cp -a "$RSPC_BIN" "$BK/rspc"
cp -a "$RSPC_CONFIG" "$BK/config.yaml"
cp -a "$RSPC_HOME/scripts" "$BK/scripts"
cp -a "$RSPC_HOME/VERSION" "$BK/VERSION" 2>/dev/null || true
for f in rspc.db rspc.db-wal rspc.db-shm secret.key; do
  if [[ -f "$RSPC_DATA/$f" ]]; then cp -a "$RSPC_DATA/$f" "$BK/$f"; fi
done
ok "backup done"

rollback() {
  warn "rolling back to $OLD_VERSION"
  systemctl stop "$RSPC_SERVICE" || true
  install -m 0755 "$BK/rspc" "$RSPC_BIN"
  rm -rf "$RSPC_HOME/scripts" && cp -a "$BK/scripts" "$RSPC_HOME/scripts"
  if [[ -f "$BK/VERSION" ]]; then cp -a "$BK/VERSION" "$RSPC_HOME/VERSION"; fi
  rm -f "$RSPC_DATA/rspc.db-wal" "$RSPC_DATA/rspc.db-shm"
  for f in rspc.db rspc.db-wal rspc.db-shm secret.key; do
    if [[ -f "$BK/$f" ]]; then cp -a "$BK/$f" "$RSPC_DATA/$f"; fi
  done
  write_unit
  systemctl start "$RSPC_SERVICE" || true
  if wait_healthy 30; then
    warn "rolled back: $OLD_VERSION is running again"
  else
    warn "old version did not start either — see: journalctl -u $RSPC_SERVICE"
  fi
}

# Errors from here on trigger a rollback instead of a plain exit.
trap 'warn "update failed (line $LINENO): $BASH_COMMAND"; rollback; exit 1' ERR

info "installing $NEW_VERSION"
install_files "$SRC_DIR"
write_unit
# migrate the database with the new binary before starting the service
rspc_cli init >/dev/null
systemctl start "$RSPC_SERVICE"

if ! wait_healthy 40; then
  show_recent_logs 40
  trap - ERR
  rollback
  die "update to $NEW_VERSION failed, previous version restored. Backup kept in $BK"
fi
trap - ERR

# keep the 5 most recent backups
mapfile -t OLD_BACKUPS < <(ls -1dt "$RSPC_BACKUPS"/*/ 2>/dev/null | tail -n +6)
for d in "${OLD_BACKUPS[@]}"; do rm -rf "$d"; done

ok "RSPC updated to $NEW_VERSION (backup: $BK)"
