#!/usr/bin/execlineb -P
# Readiness instead of "the process runs": data/check decides whether
# keepalived reached MASTER or BACKUP (see there). 60 s, because a VRRP
# election with advert_int 1 and three missed advertisements takes up to a few
# seconds and a router may come up slower.
#
# 1. Remove /run/keepalived.state BEFORE the start. The file is written by
#    keepalived-notify.sh on every transition and outlives the process: after
#    a restart the state of the PREVIOUS run was still there, and data/check
#    reported "ready" at its first try -- before the new process had even
#    read its configuration. Readiness must follow a real transition of THIS
#    run. Nothing else can hold the file open meanwhile: the previous
#    keepalived is gone when run starts, and keepalived-notify.sh writes via
#    temp file plus mv.
#
# 2. Say once per start which readiness applies. The message is HERE and not
#    in data/check, and that is measured: stderr (and stdout) of a data/check
#    run by s6-notifyoncheck do NOT reach the logger (24.09.2026).
#    s6-notifyoncheck only cares about the exit code. In the run script the
#    output goes to the logger, and "once per start" follows by itself.
foreground { rm -f /run/keepalived.state }
foreground {
  ifelse { ./data/notify-configured }
  {
    echo "keepalived-s6: keepalived-notify.sh is configured -- ready once it reports MASTER or BACKUP to /run/keepalived.state."
  }
  foreground {
    echo "keepalived-s6: keepalived-notify.sh is not configured in /etc/keepalived -- readiness is only checked at stage 1 (VRRP child process runs)."
  }
  echo "keepalived-s6: Only keepalived itself can report the VRRP STATE: keepalived-notify >= 0.1.3 writes it, called by a notify line in the configuration."
}

s6-notifyoncheck -d -n60 --
run-script-daemon keepalived
