#!/usr/bin/env sh
#
# This file is part of Reactor. https://reactor.toggledbits.com/docs/
#
# Back up Reactor data to a backup directory; keep copies up to specified age (days).
#
# Usage:  cd /path/to/reactor && tools/backup_reactor_data.sh /target/dir [max_age]
#
# Version 25280
#
# IMPORTANT! Ideally, DON'T MODIFY THIS SCRIPT WITH YOUR CONFIGURATION CHANGES.
# The things you most often need to change are command line arguments.
#
# RECOMMENDED: RUN THIS SCRIPT UNDER CRON (AND NOT ROOT)
# It is recommended that you run this script from the crontab of your Reactor
# user. Use the `crontab -e` command to edit the crontab while logged in as
# that user. The following line add to your crontab will run the script every
# day at 3am local time (refer to crontab(5) for other timing):
#
# 0 3 * * * cd /path/to/reactor && tools/backup_reactor_data.sh ~/reactor-backups
#
# WARNING: If you back up a running Reactor system within a couple of minutes of
# making changes, the changes may not be reflected in the backup, because of the
# caching Reactor does to reduce disk I/O. Stopping Reactor will ensure all cached
# data is written before a backup. But if you are backing up at 3am, as shown
# above, it probably doesn't matter, as the system is relatively inactive and The
# cache has probably been flushed of everything important.
#
# To extract these backups, use: tar xzf --directory=<where> <backup-pathname>
# RECOMMENDED: extract backups to /tmp or another scratch directory before
# overwriting data in your live configuration. Also, you can extract to a
# scratch directory and copy only parts needed (e.g. one rule or reaction).
# Make sure Reactor is stopped when overwriting/replacing data files.
#
# ------------------------------------------------------------------------------

RD=${REACTOR_DATA_PREFIX:-`pwd`}
[ -d ${RD}/config -a -d ${RD}/storage ] || {
    echo "Can't find 'config' and 'storage' directories in ${RD}";
    echo "This script must be run from the Reactor install directory. Example:";
    echo "    cd /home/pi/reactor && tools/backup_reactor_data.sh /home/pi/reactor-backups"
    echo " "
    echo "Recommended: run under 'cron'. Please see the script header for instructions."
    exit 1;
}
RR=$(dirname $0)

# Check if at least one argument (target directory) is provided
if [ $# -lt 1 ]; then
    echo "Usage: $0 <backup_directory> [max_age_in_days]"
    exit 255
fi

# Assign command line arguments/defaults.
BACKUP_DIR="$1"
MAX_AGE=${2:-30}  # Default to 30 days if second argument is not provided

# Group read-only, world nothing
umask 027

# Ensure backup directory exists
mkdir -p "$BACKUP_DIR" || { echo "Failed to create/access backup directory"; exit 1; }

# Generate tar filename with date (format: backup_YYYYMMDD.tar.gz)
DATE=$(date +%y%m%dT%H%M)
TAR_FILE="$BACKUP_DIR/reactor_data_${DATE}.tar.gz"

# Create tar backup
tar -czf "$TAR_FILE" --directory="${RD}" \
    --exclude-from=${RR}/backup_exclude.lst \
    storage config ext locales || { echo "Backup failed"; exit 1; }
echo "Backup created: $TAR_FILE"

# Remove backups older than MAX_AGE days
if [ $MAX_AGE -gt 0 ]; then
    find "$BACKUP_DIR" -name "reactor_data_*.tar.gz" -mtime +"$MAX_AGE" -delete
    echo "Removed backups older than $MAX_AGE days"
fi

exit 0
