#!/bin/bash

set -e

# Get a random number between 0 (inclusive) and the given maximum (exclusive)
# e.g. getrnd 50 => 0 - 49
getrnd() {
    echo $(($(hexdump -n 2 -e '"%1u"' /dev/urandom) % $1))
}

# Get minute for hourly cronjob
HOURLY_MINUTE=$(($(getrnd 50) + 10))   # 10 - 59
# Calculate minute for daily cronjob
DAILY_MINUTE=$((HOURLY_MINUTE + 8))    # 18 - 67
# Calculate minute for weekly cronjob
WEEKLY_MINUTE=$((HOURLY_MINUTE + 30))  # 40 - 89
# Calculate minute for monthly cronjob
MONTHLY_MINUTE=$((HOURLY_MINUTE + 35)) # 45 - 94
# Get hour for daily, weekly and monthly cronjob
HOUR=$(getrnd 6) # 0 - 5
DAILY_HOUR=${HOUR}
# Check if minute of daily cronjob is too big
if [ "${DAILY_MINUTE}" -ge 60 ]; then
    # Wrap minute of daily cronjob
    DAILY_MINUTE=$(printf "%2d" "$((DAILY_MINUTE % 60))")
    # Increase hour of daily cronjob
    DAILY_HOUR=$((DAILY_HOUR + 1))
fi
WEEKLY_HOUR=${HOUR}
# Check if minute of weekly cronjob is too big
if [ "${WEEKLY_MINUTE}" -ge 60 ]; then
    # Wrap minute of weekly cronjob
    WEEKLY_MINUTE=$(printf "%2d" "$((WEEKLY_MINUTE % 60))")
    # Increase hour of weekly cronjob
    WEEKLY_HOUR=$((WEEKLY_HOUR + 1))
fi
MONTHLY_HOUR=${HOUR}
# Check if minute of monthly cronjob is too big
if [ "${MONTHLY_MINUTE}" -ge 60 ]; then
    # Wrap minute of monthly cronjob
    MONTHLY_MINUTE=$(printf "%2d" "$((MONTHLY_MINUTE % 60))")
    # Increase hour of monthly cronjob
    MONTHLY_HOUR=$((MONTHLY_HOUR + 1))
fi

# Check if backup of original crontab exists
if [ ! -e /etc/crontab.orig ]; then
    # Create backup of original crontab
    echo "Creating backup of /etc/crontab to /etc/crontab.orig"
    cp /etc/crontab /etc/crontab.orig
fi

echo "Randomizing /etc/crontab"
# Search and replace crontab in place
sed --in-place --regexp-extended \
    --expression="s/17(\s*)\*(\s*)\*(\s*)\*(\s*)\*(\s*)root/${HOURLY_MINUTE}\1*\2*\3*\4*\5root/g" \
    --expression="s/25(\s*)6(\s*)\*(\s*)\*(\s*)\*(\s*)root/${DAILY_MINUTE}\1${DAILY_HOUR}\2*\3*\4*\5root/g" \
    --expression="s/47(\s*)6(\s*)\*(\s*)\*(\s*)7(\s*)root/${WEEKLY_MINUTE}\1${WEEKLY_HOUR}\2*\3*\47\5root/g" \
    --expression="s/52(\s*)6(\s*)1(\s*)\*(\s*)\*(\s*)root/${MONTHLY_MINUTE}\1${MONTHLY_HOUR}\21\3*\4*\5root/g" \
    /etc/crontab

#if diff /etc/crontab.orig /etc/crontab > /dev/null 2>&1;
echo "Successfully randomized /etc/crontab"
#fi
