#!/usr/bin/env bash
# archivmail — schreibt paused_hours nach /etc/archivmail/config.yml und
# stößt per SIGHUP (systemctl reload) einen Reload an, damit der OCR-Worker
# das neue Fenster übernimmt — ohne SMTP/IMAP/API-Verbindungen zu kappen.
#
# Aufruf (siehe deploy/cron.d/archivmail-ocr-pause):
#   archivmail-ocr-pause.sh start <from_hour> <to_hour>
#   archivmail-ocr-pause.sh stop
set -euo pipefail

CONFIG="/etc/archivmail/config.yml"
SERVICE="archivmail"

if [ ! -f "$CONFIG" ]; then
    echo "archivmail-ocr-pause: $CONFIG nicht gefunden" >&2
    exit 1
fi

cmd="${1:-}"

case "$cmd" in
start)
    from="${2:?from_hour fehlt}"
    to="${3:?to_hour fehlt}"
    if ! grep -q "^ocr:" "$CONFIG"; then
        printf '\nocr:\n  paused_hours: [%s, %s]\n' "$from" "$to" >> "$CONFIG"
    elif grep -q "paused_hours:" "$CONFIG"; then
        sed -i -E "s/^([[:space:]]*paused_hours:).*/\1 [${from}, ${to}]/" "$CONFIG"
    else
        sed -i "/^ocr:/a\\  paused_hours: [${from}, ${to}]" "$CONFIG"
    fi
    ;;
stop)
    sed -i -E "s/^([[:space:]]*paused_hours:).*/\1 null/" "$CONFIG"
    ;;
*)
    echo "Usage: $0 {start <from_hour> <to_hour>|stop}" >&2
    exit 1
    ;;
esac

systemctl reload "$SERVICE"
