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

# Install the wp-update-queue worker cron entry.
#
# Prior to this, the Update Now flow on the WordPress Management page that
# bundles a backup-before-update would queue the update into wp_update_queue
# (status='waiting_for_backup') but no consumer existed. Backup completed,
# update never fired, wp_update_history sat at 'in_progress' forever.

CRON_LINE='* * * * * /usr/bin/flock -n /run/whp-wp-update-queue.lock /usr/bin/timeout 300 /usr/bin/php /docker/whp/web/scripts/wp-update-queue-worker.php >/dev/null 2>&1'
CRON_TAG='wp-update-queue-worker.php'
LOG_FILE='/var/log/whp-wp-update-queue.log'

# Touch the log file so the worker can append without root-only perms surprises
touch "$LOG_FILE"
chmod 640 "$LOG_FILE"

# Idempotent install: replace any existing line referencing this worker
existing_cron=$(crontab -l 2>/dev/null || true)
filtered_cron=$(printf '%s\n' "$existing_cron" | grep -v -F "$CRON_TAG" || true)

# Append the canonical entry
new_cron=$(printf '%s\n%s\n' "$filtered_cron" "$CRON_LINE")

# Drop blank leading lines
printf '%s\n' "$new_cron" | sed '/./,$!d' | crontab -

echo "Installed wp-update-queue-worker cron entry"
crontab -l | grep -F "$CRON_TAG" || {
    echo "ERROR: cron entry not found after install" >&2
    exit 1
}

exit 0
