#!/bin/sh

# This restic-backup-cron script is called from cron on a regular
# basis to backup files from here to there.

# Copyright 2023 Bob Proulx <bob@proulx.com>
#
# Copying and distribution of this file, with or without modification,
# are permitted in any medium without royalty provided the copyright
# notice and this notice are preserved.  This file is offered as-is,
# without any warranty.
#
# Written by Bob Proulx <bob@proulx.com>

whoami=$(whoami)
lock=/tmp/restic-backup-cron-$whoami.lock
mailto=$whoami

# Check for stale locks.
if [ -e "$lock" ]; then
    if [ -n "$(find "$lock" -mtime +1 -print 2>/dev/null)" ]; then
        : Older lock file found.  Must be stale.  Complain.
        echo "Old lock found.  Stale?" 1>&2
        ls -ld "$lock" 1>&2
        exit 1
    fi
fi

# Atomic test-and-set operation 'mkdir' used as a semaphore.
if ! mkdir "$lock" 2>/dev/null; then
    : Another process got the semaphore and is now running.  They run, we exit.
    exit 0
fi
: "debug: Semaphore $lock created."

# On exit remove the flag saying we are running.

unset tmpfile
cleanup() {
    rmdir "$lock"
    test -n "$tmpfile" && rm -f "$tmpfile" && unset tmpfile
}
sighandler() {
    echo "$progname: signal $1 received, cleaning up." 1>&2
    cleanup
    trap - $1                 # reset to default
    kill -$1 $$               # exit due to signal
}
trap 'cleanup' EXIT
trap 'sighandler HUP' HUP
trap 'sighandler INT' INT
trap 'sighandler QUIT' QUIT
trap 'sighandler TERM' TERM

tmpfile=$(mktemp) || exit 1

exec </dev/null >"$tmpfile" 2>&1

# Source in the ssh keys using keychain.  Only the user has
# permission to read these files.
hostname=$(hostname)            # Possible FQDN here.
host=${hostname%%.*}            # Just the short name.
if [ -f $HOME/.keychain/$host-sh ]; then
    . $HOME/.keychain/$host-sh
fi

# Test that we have ssh keys available.
if ! ssh-add -ql >/dev/null 2>&1; then
    # If we do not then do not try to back up.  Exit.  Try again next time.
    exit 0
fi

# This backs up each of the named directories.  The files to be backed
# up must all be readable by the user running this.

restic-backup-wrap -q $HOME

exec >/dev/null 2>&1            # close previous output file

if [ -s "$tmpfile" ]; then
    # There was output.  Mail it.
    mailx -s "$(hostname): restic backup output" "$mailto" < "$tmpfile"
fi

# Cron scripts should always exit success even if there was a failure
# because cron is not equipped to deal with it other than email the
# caller and we already emailed the responsible party in the above.
exit 0
