#!/bin/bash

[ "$UID" != "0" ] && echo "You must be root." 2>&1  && exit 1

##
## code
##


user=rsync
src="$1"

if [ -z "$src" ]; then
    echo "You must provide a source directory as first argument." >&2
    exit 1
fi

if ! [ -d "$src" ]; then
    echo "Folder '$src' not found, please provide a valid directory as first argument." >&2
    exit 1
fi

dest="$2"

if [ -z "$dest" ]; then
    echo "You must provide a host as target." >&2
    exit 1
fi


rsync_options=(${RSYNC_OPTIONS:-})
ssh_options=(${SSH_OPTIONS:--o StrictHostKeyChecking=no})


if echo "$dest" | grep "/" >/dev/null 2>&1; then
    rsync_options=("--bwlimit" "$(echo "$dest" | cut -f 2 -d "/")" "${rsync_options[@]}")
    dest="$(echo "$dest" | cut -f 1 -d "/")"
fi

if echo "$dest" | grep ":" >/dev/null 2>&1; then
    ssh_options=("-p" "$(echo "$dest" | cut -f 2 -d ":")" "${ssh_options[@]}")
    dest="$(echo "$dest" | cut -f 1 -d ":")"
fi


hostname=$(hostname)
hostname=${LABEL_HOSTNAME:-$hostname}

dest_path="/var/mirror/$hostname"

touch /etc/rsync/exclude-patterns
touch /etc/rsync/include-patterns

if ! [ -s "/etc/rsync/include-patterns" ]; then
    echo "Nothing to do as /etc/rsync/include-patterns is empty."
    exit 0
fi

cmd=(/usr/bin/rsync "${rsync_options[@]}" -azvA
     -e "sudo -u $user ssh ${ssh_options[*]}"
     --include-from /etc/rsync/include-patterns
     --exclude-from /etc/rsync/exclude-patterns
     --delete --partial --partial-dir .rsync-partial
     --numeric-ids "$src/" "$user@$dest":"$dest_path")

rsync_uid_gid=$(stat -c "%u:%g" "/var/lib/rsync")
chown "$rsync_uid_gid" "/var/lib/rsync/.ssh" -R

echo "${cmd[@]}"

exec "${cmd[@]}"