#!/bin/bash

set -eu
set -o pipefail
set -x

line="0 0 * * * /home/dstromberg/bin/page-change"

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

# If our crontab is empty, this exits false
crontab -l > "$tempfile" || true

if sed 's/#.*//' "$tempfile" | awk '$6 == "/home/dstromberg/bin/page-change" || $6 == "/home/dstromberg/bin/page-change" { print }' | grep -q .
then
    awk '$6 != "/home/dstromberg/bin/page-change" && $6 != "/home/dstromberg/bin/page-change" { 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