#!/bin/bash
 
SERVERNAME="[SERVERNAME]"
EMAIL="[MAIL@ADRESSE]"
 
WHICH="$(/usr/bin/which which)"
ECHO="$($WHICH echo)"
RESTIC="$($WHICH restic)"
TOUCH="$($WHICH touch)"
MAILX="$($WHICH mailx)"
RM="$($WHICH rm)"
MOUNT="$($WHICH mount)"
GREP="$($WHICH grep)"
PWDFILE="/root/.resticpwd"
REP=("repository1" "ggf. weitere")
BACKUP_PATH=("/backup/pfad/1" "/ggf/weitere /auch/mehrere")
OPTIONS="--compression max"
OPTCLEAN="--keep-last 2 --prune"
 
mail_on_error()
{
  if [ "$1" -ne 0 ]; then
    $ECHO "Fehler bei $3 $2" | $MAILX -s "Fehler: Restic $SERVERNAME ($3)" $EMAIL
    $RM $LOCK
    exit 0
  fi
}
 
for i in ${BACKUP_PATH[$1]}
  do
    if ! [ $MOUNT | $GREP $i ]; then
      mail_on_error 1 $i Mountpoint
      exit 0
    fi
  done
 
if [ ! -f $1 ]; then
  case $1 in
    [0-3])
      LOCK="/var/run/backup$1.lock"
      if [ ! -f $LOCK ]; then
        $TOUCH $LOCK
        $RESTIC $OPTIONS -p $PWDFILE -r ${REP[$1]} backup ${BACKUP_PATH[$1]} 2>&1 >> /tmp/restic$1.log
        mail_on_error $? ${BACKUP_PATH[$1]} Backup
        $RESTIC forget $OPTCLEAN -p $PWDFILE -r ${REP[$1]} 2>&1 >>/tmp/restic$1.log
        mail_on_error $? ${BACKUP_PATH[$1]} Cleanup
        $RM $LOCK
      fi
    ;;
    *)
      exit 0
    ;;
  esac
fi