#!/bin/sh -e

if ! command -v rsync > /dev/null
then
    echo 'rsync is missing in local machine' >&2
    exit 1
fi

src="$( cat "$__object/parameter/source" )"

if [ ! -e "$src" ]
then
    echo "$src not found" >&2
    exit 1
fi

if [ -f "$__object/parameter/destination" ]
then
    dst="$( cat "$__object/parameter/destination" )"
else
    dst="/$__object_id"
fi

# if source is directory, then make sure that
# source and destination are ending with slash,
# because this is what you almost always want when
# rsyncing two directories.

if [ -d "$src" ]
then
    if ! echo "$src" | grep -Eq '/$'
    then
        src="$src/"
    fi

    if ! echo "$dst" | grep -Eq '/$'
    then
        dst="$dst/"
    fi
fi

remote_user="$( cat "$__object/parameter/remote-user" )"

options="$( cat "$__object/parameter/options" )"

if [ -f "$__object/parameter/option" ]
then
    while read -r l
    do
        # there's a limitation in argparse: value can't begin with '-'.
        # to workaround this, let's prefix opts with '\' in manifest and remove here.
        # read more about argparse issue: https://bugs.python.org/issue9334

        options="$options $( echo "$l" | sed 's/\\//g' )"
    done \
        < "$__object/parameter/option"
fi

if [ -f "$__object/parameter/owner" ] || [ -f "$__object/parameter/group" ]
then
    options="$options --chown="

    if [ -f "$__object/parameter/owner" ]
    then
        owner="$( cat "$__object/parameter/owner" )"
        options="$options$owner"
    fi

    if [ -f "$__object/parameter/group" ]
    then
        group="$( cat "$__object/parameter/group" )"
        options="$options:$group"
    fi
fi

if [ -f "$__object/parameter/mode" ]
then
    mode="$( cat "$__object/parameter/mode" )"
    options="$options --chmod=$mode"
fi

# IMPORTANT
#
# 1. we first dry-run rsync with change summary to find out
#    if there are any changes and code generation is needed.
# 2. normally, to get current state or target host, we run
#    such operations in type explorers, but that's not
#    possible due to how rsync works.
# 3. redirecting output of dry-run to stderr to ease debugging.
# 4. to understand how that cryptic regex works, please
#    open rsync manpage and read about --itemize-changes.

export RSYNC_RSH="$__remote_exec"

# shellcheck disable=SC2086
if ! rsync --dry-run --itemize-changes $options "$src" "$remote_user@$__target_host:$dst" \
    | grep -E '^(<|>|c|h|\.|\*)[fdL][cstTpogunbax\.\+\?]+\s' >&2
then
    exit 0
fi

echo "export RSYNC_RSH='$__remote_exec'"

echo "rsync $options $src $remote_user@$__target_host:$dst"
