#!/bin/bash
# Run inside merchant container (as root).
# Restarts taler-merchant-wirewatch when it exits.
# Without systemd, wirewatch exits on PG config NOTIFY and would stay down.
set +e
LOG=/var/log/taler-merchant/wirewatch-supervise.log
WW_LOG=/var/log/taler-merchant/wirewatch.log
CONF="${TALER_MERCHANT_CONFIG:-/etc/taler-merchant/taler-merchant.conf}"
mkdir -p /var/log/taler-merchant
echo "$(date -u +%FT%TZ) supervise start" >>"$LOG"
for p in $(ps -eo pid=,args= | awk '$2=="/usr/bin/taler-merchant-wirewatch"{print $1}'); do
  kill "$p" 2>/dev/null || true
done
sleep 1
while true; do
  echo "$(date -u +%FT%TZ) start wirewatch" >>"$LOG"
  if [ "$(id -un)" = "root" ]; then
    runuser -u taler-merchant-httpd -- /usr/bin/taler-merchant-wirewatch -c "$CONF" -L INFO >>"$WW_LOG" 2>&1
    ec=$?
  else
    /usr/bin/taler-merchant-wirewatch -c "$CONF" -L INFO >>"$WW_LOG" 2>&1
    ec=$?
  fi
  echo "$(date -u +%FT%TZ) wirewatch exit=$ec; sleep 2" >>"$LOG"
  sleep 2
done
