#!/usr/bin/env bash
# setup-luks-header-backup-cron.sh — install the daily LUKS header backup cron.
#
# Header backup is critical for recovery from header corruption. Runs daily
# (header rarely changes; only on passphrase rotation, so most runs are no-ops).
# Wrapped with flock+timeout per WHP cron convention.
#
# Idempotent. Skips on non-LUKS servers.

set -euo pipefail

if [ ! -f /etc/whp/luks.conf ]; then
    echo "setup-luks-header-backup-cron.sh: /etc/whp/luks.conf not present — skipping (non-LUKS server)"
    exit 0
fi

SCRIPT_PATH=/root/whp/scripts/luks-header-backup.sh
LOCK_FILE=/run/whp-luks-header-backup.lock
LOG_FILE=/var/log/whp/luks-header-backup.log
CRON_LINE="17 3 * * * /usr/bin/flock -n $LOCK_FILE /usr/bin/timeout 120 $SCRIPT_PATH >> $LOG_FILE 2>&1"
CRON_MARKER="luks-header-backup.sh"

if [ ! -x "$SCRIPT_PATH" ]; then
    echo "ERROR: $SCRIPT_PATH not found or not executable. Aborting." >&2
    exit 1
fi

mkdir -p /var/log/whp
touch "$LOG_FILE"
chmod 0644 "$LOG_FILE"

# Idempotent crontab merge — drop any existing line for this script, then
# add ours. Preserves all other entries.
CURRENT=$(crontab -l 2>/dev/null || true)
UPDATED=$(printf '%s\n' "$CURRENT" | grep -vF "$CRON_MARKER" || true)
# Add the new line
UPDATED=$(printf '%s\n%s\n' "$UPDATED" "$CRON_LINE")
# Remove blank lines (printf creates a leading blank when CURRENT was empty)
UPDATED=$(printf '%s\n' "$UPDATED" | sed '/^$/d')
printf '%s\n' "$UPDATED" | crontab -

echo "Installed daily cron: $CRON_LINE"
