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

# Install daily Bichon archival reconciliation cron.
# Runs at 04:13 UTC every day. flock + timeout per WHP cron convention.

LINE='13 4 * * * /usr/bin/flock -n /run/whp-bichon-sync.lock /usr/bin/timeout 300 /root/whp/scripts/bichon-archival-sync.sh'

# Ensure /var/log/whp exists with sensible perms (script writes there).
mkdir -p /var/log/whp
chmod 0755 /var/log/whp

# Ensure the script is executable (it should be from rsync, but belt-and-suspenders).
if [ -f /root/whp/scripts/bichon-archival-sync.sh ]; then
  chmod +x /root/whp/scripts/bichon-archival-sync.sh
fi

# Install crontab entry idempotently. Match by command-tail (the path) so changes to the
# schedule prefix don't duplicate entries.
TMP=$(mktemp)
crontab -l 2>/dev/null > "$TMP" || true

if grep -F "/root/whp/scripts/bichon-archival-sync.sh" "$TMP" >/dev/null 2>&1; then
  # Replace any existing entry pointing at our script with the canonical line.
  grep -vF "/root/whp/scripts/bichon-archival-sync.sh" "$TMP" > "$TMP.new"
  mv "$TMP.new" "$TMP"
fi

echo "$LINE" >> "$TMP"
crontab "$TMP"
rm -f "$TMP"

echo "Installed bichon-archival-sync cron: $LINE"
