#!/bin/bash
# Duplicity full backup

# Varibles
SERVER_IP="" # IP of remote server
INPUT_PATH="" # Absolute Path to backup
EXCLUDE_PATTERN="" # Absolute Path to to Exclude, can be left as ""
REMOTE_USER="" # User on remote server
REMOTE_PATH="" # Absolute Path on the remote server to backup to. If path has a ' ' in it add '"'s around the '$REMOTE_PATH's bellow

# Sets Varibles for log files
DATE=$(date +%Y-%m-%d-%H-%M-%S)
LOG_FILE="/var/log/duplicity/${DATE}.log"

export PASSPHRASE= # Passphrase for backup encryption

# Pings server IP to see if it is online
ping -c 1 "$SERVER_IP" > /dev/null 2>&1

# If online run backup
if [ $? -eq 0 ]; then
	echo "$(date) Server $SERVER_IP is online" >> "$LOG_FILE"

	# Cleanup anything older than 21 days
	echo "Running Cleanup"  >> "$LOG_FILE" 2>&1
	duplicity remove-older-than 14D -v9 --force scp://${REMOTE_USER}@${SERVER_IP}/$REMOTE_PATH >> "$LOG_FILE" 2>&1

	# Log whether or not it was sucessfull
    if [ $? -eq 0 ]; then
        echo "$(date) Cleanup successful" >> "$LOG_FILE"
    else
        echo "$(date) Cleanup failed" >> "$LOG_FILE"
    fi

	# If there EXCLUDE_PATTERN is not null then set the duplicity arguments with the pattern, else set without
	if [ -n "$EXCLUDE_PATTERN" ]; then
		ARGS="--exclude $EXCLUDE_PATTERN $INPUT_PATH"
	else
		ARGS="$INPUT_PATH"
	fi

	duplicity full $ARGS scp://${REMOTE_USER}@${SERVER_IP}/$REMOTE_PATH >> "$LOG_FILE" 2>&1

	# Log whether or not it was sucessfull
    if [ $? -eq 0 ]; then
        echo "$(date) Backup successful" >> "$LOG_FILE"
    else
        echo "$(date) Backup failed" >> "$LOG_FILE"
    fi

# If not online report in log
else
    echo "$(date) Server $SERVER_IP is offline" >> "$LOG_FILE"
fi

# Gotify Notification
TITLE="$(hostname) backup"
PRIORITY=0
URL="http://:/message?token="
LOG_CONTENT=$(cat "$LOG_FILE")

curl -s -S --data-urlencode "title=$TITLE" --data-urlencode "message=$LOG_CONTENT" "$URL"
