#!/bin/bash
# rsyncs a path to a remote server

# Sets Varibles that can be changed
SERVER_IP="" # IP of remote server
INPUT_PATH="" # Absolute Path to backup
EXCLUDE_PATTERN="" #Relitive path to INPUT_PATH 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 dont use "" or ''

GOTIFY_IP=""
GOTIFY_PORT=""
GOTIFY_TOKEN=""

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

# 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"

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

    # Run the rsync
    rsync $RSYNC_ARGS $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://$GOTIFY_UP:$GOTIFY_PORT/message?token=$GOTIFY_TOKEN"
LOG_CONTENT=$(cat "$LOG_FILE")

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