bup-backup-sync/bup-sync-trigger.sh
2024-05-09 13:38:21 +02:00

125 lines
2.3 KiB
Bash
Executable File

#!/bin/bash -e
# Parse CLI and set options
repoFile="$(dirname "$0")/repos"
dryRun=''
varDir=/var/lib/bup-backup-trigger
triggerFile="$varDir/trigger"
lockFile="$varDir/lock"
log="/var/log/bup-sync.log"
mkdir -p "$varDir"
while [ $# -gt 0 ]
do
case "$1" in
--repos|-r)
repoFile="$2"
shift
;;
--dry|--dry-run|-d)
dryRun=y
;;
--lock)
touch "$lockFile"
exit 0
;;
--unlock)
rm -f "$lockFile"
exit 0
;;
--log)
log="$2"
shift
;;
*)
echo "Cannot understand parameter \"$1\". Aborting." >&2
exit 1
;;
esac
shift
done
if [ "$log" != '-' ]
then
exec >> "$log"
fi
# Do some safety checks
if [ ! -r "$repoFile" ]
then
echo "Cannot read the file $repoFile. Exiting" >&2
exit 1
fi
if [ -f "$lockFile" ]
then
echo "The lock file exists. Skipping for now ($(date))"
exit 0
fi
# Define the needed functions
getNextDate() {
python << EOF
import datetime
now = datetime.date.today()
weekday = now.weekday()
oneDay = datetime.timedelta(days=1)
mondayThisWeek = now - oneDay * weekday
mondayNextWeek = mondayThisWeek + oneDay * 7
dt = datetime.datetime.fromisoformat(mondayNextWeek.isoformat())
dt = dt.replace(hour=4, minute=45)
print(int(dt.astimezone(datetime.timezone.utc).timestamp()))
EOF
}
updateTriggerFile() {
getNextDate > "$triggerFile"
}
triggerLiesInPast() {
if [ ! -f "$triggerFile" ]
then
return 0
fi
local now=$(date +%s)
local triggered=$(cat "$triggerFile")
if [ $now -gt "$triggered" ]
then
return 0
else
return 1
fi
}
if ! triggerLiesInPast
then
echo "The timestamp in the trigger event lies in the future. Waiting further."
exit 0
fi
echo "The backup script is triggered."
while read line
do
echo "Processing line $line"
if [ -n "$dryRun" ]
then
echo "Shipping to call script $line as in dry mode."
else
$line
fi
done <<< $(cat "$repoFile" | grep -v '^#' | sed '/^\W*$/d')
if [ -n "$dryRun" ]
then
echo "Not updating the trigger timestamp. The value would be $(getNextDate)."
else
updateTriggerFile
fi