#!/usr/bin/env bash
set -Euo pipefail

CONFIG_FILE="${XDG_CONFIG_HOME:-$HOME/.config}/hermes-stack-maintenance/config.env"
STATE_DIR="${XDG_STATE_HOME:-$HOME/.local/state}/hermes-stack-maintenance"
NOTIFIER="$HOME/.local/libexec/hermes-stack-notify"
mkdir -p "$STATE_DIR"
# shellcheck disable=SC1090
source "$CONFIG_FILE"

set +u
set -a
# shellcheck disable=SC1090
source "$HERMES_ENV" || true
set +a
set -u

state_file="$STATE_DIR/signal-health-state"
signal_url="${SIGNAL_HTTP_URL:-}"
[[ -n "$signal_url" ]] || exit 0

check_signal() {
  local status
  status="$(curl --silent --output /dev/null --max-time 5 \
    --write-out '%{http_code}' "${signal_url%/}/api/v1/check" || true)"
  [[ "$status" =~ ^2[0-9][0-9]$ ]]
}

if check_signal; then
  current=healthy
else
  systemctl --user restart "$SIGNAL_SERVICE" || true
  sleep 5
  check_signal && current=healthy || current=unhealthy
fi

previous="$(cat "$state_file" 2>/dev/null || true)"
if [[ "$current" == unhealthy && "$previous" != unhealthy ]]; then
  "$NOTIFIER" "Hermes-Stack: signal-cli ist nicht erreichbar; Neustart wurde versucht." || true
elif [[ "$current" == healthy && "$previous" == unhealthy ]]; then
  "$NOTIFIER" "Hermes-Stack: signal-cli ist wieder erreichbar." || true
fi

printf '%s\n' "$current" >"$state_file"
[[ "$current" == healthy ]]
