#!/bin/bash -e

# Inform user
echo "Welcome to tupper! Running on $(date)"

# Check if it is clear what to do
ACTION="$1"
if [ "$ACTION" != "backup" ] && [ "$ACTION" != "initialize" ]; then
	echo "tupper requires an action: $0 { initialize | backup }" 1>&2
	echo "Unrecognized action: $ACTION" 1>&2
	exit 1
fi

# Check access rights of config file
CONF="/etc/tupper.conf"
if [ "$(stat -c '%U' $CONF)" != "root" ] && [ "$(stat -c '%A' $CONF)" = "*------" ]; then
	echo "Config file $CONF must be owned by root without any rights for group and other (**00)  set" 1>&2
	exit 1
fi
# Include config file
source "$CONF"

# Check if required variables are set
if [ "$SSH_URI" = "" ] || [ "$SSH_PASS" = "" ] || [ "$TARGET" = "" ]; then
	echo "Config file $CONF must contain SSH_URI, SSH_PASS and TARGET" 1>&2
	exit 1
fi

# Check privileges
if [ "$UID" -ne 0 ]; then
	echo "$0 must be run as root. Quitting." 1>2
	exit 1
fi

# Create temporary mountpoint
MOUNTPOINT="$(mktemp --directory)"

# Check if SSHFS needs to be mounted
if [ "$(mount | grep $MOUNTPOINT | wc -l)" -eq 0 ]; then
	echo "$SSH_PASS" | sshfs -o password_stdin "$SSH_URI" "$MOUNTPOINT"
fi

# Backup
export BORG_PASSPHRASE
export BORG_RELOCATED_REPO_ACCESS_IS_OK=yes
if [ "$ACTION" = "initialize" ]; then
	borg init --encryption=repokey "$TARGET"
elif [ "$ACTION" = "backup" ]; then
	borg create --stats "$MOUNTPOINT::"'{now}' "$TARGET"
	borg prune --list --show-rc --keep-daily 7 --keep-weekly 4 --keep-monthly 3 "$MOUNTPOINT"
	borg list "$MOUNTPOINT"
fi

# Unmount and clean up mountpoint
fusermount -u "$MOUNTPOINT" && \
rm -rf "$MOUNTPOINT"

# Inform user
echo "Goodbye from tupper! Finished on $(date)"
