#!/usr/bin/env bash
# Extend the per-cron `timeout` cap for the three WHP backup-related crons
# from 240s to 600s. The backup workers now run tar/pigz/mysqldump under
# `ionice -c3` (idle I/O class) so they yield to live traffic — that means
# a job can take noticeably longer when the host is under sustained read
# load, and the old 240s cap will start tripping early.
#
# This script edits the existing crontab in place. It anchors on the
# specific lock-file name that wrap-per-minute-crons.sh installed, so
# only the three backup workers are touched and unrelated entries with
# the same timeout value are not.
#
# Idempotent: re-running after the cap is already 600s is a no-op.

set -euo pipefail

# lock_basename|new_timeout
ENTRIES=(
    "whp-backup-worker|600"
    "whp-backup-upload|600"
    "whp-backup-scheduler|600"
)

CURRENT="$(crontab -l 2>/dev/null || true)"
if [[ -z "${CURRENT}" ]]; then
    echo "No crontab installed for $(whoami) — nothing to do."
    exit 0
fi

NEW="${CURRENT}"

bump_one() {
    local lockbase="$1"
    local new_secs="$2"
    local lockfile="/run/${lockbase}.lock"

    # Find existing flock-wrapped line for this lock.
    local matched
    matched="$(echo "${NEW}" | grep -F "/usr/bin/flock -n ${lockfile}" || true)"
    if [[ -z "${matched}" ]]; then
        echo "  ${lockbase}: not found in crontab (run wrap-per-minute-crons.sh first?), skipping"
        return 0
    fi

    while IFS= read -r line; do
        [[ -z "${line}" ]] && continue

        # Extract the existing timeout value: ".../flock -n LOCK /usr/bin/timeout NNN ..."
        local current_secs
        current_secs="$(echo "${line}" | sed -n "s|.*/usr/bin/flock -n ${lockfile} /usr/bin/timeout \([0-9]\+\).*|\1|p")"
        if [[ -z "${current_secs}" ]]; then
            echo "  ${lockbase}: line found but timeout field couldn't be parsed, skipping"
            continue
        fi
        if [[ "${current_secs}" == "${new_secs}" ]]; then
            echo "  ${lockbase}: already at ${new_secs}s, skipping"
            continue
        fi

        # Build replacement line: same prefix, swap the timeout value.
        local new_line="${line/\/usr\/bin\/timeout ${current_secs} /\/usr\/bin\/timeout ${new_secs} }"

        NEW="$(echo "${NEW}" | awk -v old="${line}" -v new="${new_line}" '{
            if ($0 == old) { print new } else { print $0 }
        }')"
        echo "  ${lockbase}: ${current_secs}s -> ${new_secs}s"
    done <<< "${matched}"
}

echo "Extending backup cron timeouts to 600s..."
for e in "${ENTRIES[@]}"; do
    IFS='|' read -r lockbase secs <<< "${e}"
    bump_one "${lockbase}" "${secs}"
done

if [[ "${NEW}" == "${CURRENT}" ]]; then
    echo "No changes — crontab already at the desired timeouts."
else
    echo "${NEW}" | crontab -
    echo "Updated crontab installed."
fi

echo "extend-backup-cron-timeouts.sh: OK"
