#!/bin/sh
# Copyright (c) 2026 Athan Clark. SPDX-License-Identifier: GPL-3.0-only
# Brings the OpenChronology database up to this version's schema, then restarts the
# openchronology-server service when it runs, and the mail worker's, the syslog receiver's and
# the GitHub receiver's launchd agents, each when it is started (openchronology-agent), so that they run this version
# too (#371, #374). Safe to run more than once.
# Usage: openchronology-migrate [--no-restart]   (--no-restart restarts nothing)
set -eu
PREFIX=@HOMEBREW_PREFIX@
CONFIG=$PREFIX/etc/openchronology/openchronology.env
if [ ! -r "$CONFIG" ]; then
  echo "$CONFIG is missing: run openchronology-setup." >&2
  exit 1
fi
# The configuration is read as systemd reads it (OCH_CONFIG, #118).
OCH_CONFIG="$CONFIG" "@NODE@" "@LIBEXEC@/server/migrate.mjs"
if [ "${1:-}" != "--no-restart" ] &&
  "$PREFIX/bin/brew" services list 2>/dev/null | grep -q '^openchronology-server .*started'; then
  "$PREFIX/bin/brew" services restart openchronology-server >/dev/null
  echo "OpenChronology restarted."
fi
[ "${1:-}" = "--no-restart" ] && exit 0
for worker in "mail:mail worker" "syslog:syslog receiver" "github:GitHub receiver"; do
  if launchctl print "gui/$(id -u)/org.openchronology.${worker%%:*}" >/dev/null 2>&1; then
    "$PREFIX/bin/openchronology-agent" restart "${worker%%:*}" >/dev/null
    echo "OpenChronology ${worker#*:} restarted."
  fi
done
