#!/bin/bash

set -eu
set -o pipefail
set -x

case "$(hostname)" in
    @dstromberg-precision-3530)
        # We patch these at noon, because GG likes to turn off and/or suspend them at night.
        # We don't patch in the early evening, because of OC Python.
        hour=12
        ;;
    *)
        hour=2
        ;;
esac

line="0 $hour * * * /usr/local/bin/patch-system-with-email"

tempfile=/tmp/patch-system.temp.$$
# The 0 makes $tempfile get removed on script graceful exit
# shellcheck disable=SC2064
trap "rm -f $tempfile" $(seq 0 15)

# If root's crontab is empty, this exists false
crontab -l > "$tempfile" || true

if sed 's/#.*//' "$tempfile" | awk '$6 == "/usr/local/bin/patch-system-with-email" || $6 == "/usr/local/bin/patch-system" { print }' | grep -q .
then
    awk '$6 != "/usr/local/bin/patch-system-with-email" && $6 != "/usr/local/bin/patch-system" { print }' "$tempfile" > "$tempfile".without
    mv "$tempfile".without "$tempfile"
    echo "$line" >> "$tempfile"
    crontab "$tempfile"
    exit 0
else
    echo "$line" >> "$tempfile"
    # This replaces the crontab with $tempfile
    crontab "$tempfile"
    exit 0
fi