#!/usr/bin/bash

set -eu -o pipefail

# Randomize auto-update hour to spread load across ePortal.
# Instead of all agents checking at */4 (0,4,8,12,16,20), randomly pick
# one of four hour-offset schedules to distribute requests evenly.

KCARE_CRONFILE=/etc/cron.d/kcare-cron

if [[ ! -f "$KCARE_CRONFILE" ]]; then
    exit 0
fi

if ! grep -qE '^[0-9]+[[:space:]]+\*/4[[:space:]]' "$KCARE_CRONFILE"; then
    exit 0
fi

case $(( RANDOM % 4 )) in
    0) HOURS='0,4,8,12,16,20' ;;
    1) HOURS='1,5,9,13,17,21' ;;
    2) HOURS='2,6,10,14,18,22' ;;
    3) HOURS='3,7,11,15,19,23' ;;
esac

sed -Ei 's/^([0-9]+[[:space:]]+)\*\/4([[:space:]])/\1'"$HOURS"'\2/' "$KCARE_CRONFILE"
