#!/usr/bin/env bash

error() {
    echo -e "Error: $1\nUpdating failed"
    exit 1
}

warning() {
    echo "Warning: $1"
    exit 1
}

[ $# -gt 0 ] || { echo "Usage: $0 <file>"; exit 1; }

. "$1"

[ "$host" ] || error "Host field not set in $1";
[ "$collection" ] || error "Collection field not set in $1";
[ "$destination" ] || error "Destination field not set in $1";

declare -A old_checkouts new_checkouts
if [ -e "$destination/.checkouts" ]; then
    { while read -r co; do
        old_checkouts["$co"]=1
    done } < "$destination/.checkouts" \
	    || error "Couldn't read checkouts from $destination/.checkouts"
fi

printf "Updating file list from %s::%s\n" "$host" "$collection"

# get the remote file list (new .checkouts)
rm -f "$destination/.new_checkouts"
{ while read -r nc; do
    if [ "${nc:0:5}" = "MOTD:" ] || [ "${nc:43}" = "." ]; then continue; fi;
    echo "${nc:43}" >> "$destination/.new_checkouts";
    new_checkouts["${nc:43}"]=1;
done || error "Running rsync failed"; } \
	< <(rsync -crz --no-human-readable "${host}::${collection}")

printf "Updating collection %s\n" "${destination##*/}"

# now really run rsync
rsync -crz --no-human-readable --log-format "%o %n" "${host}::${collection}" "${destination}" \
    | while read -r line; do
         [ "${line:0:5}" != "recv " ] && continue
	 (( old_checkouts["${line:5}"]==1 )) && line=" Edit ${line:5}" \
              || line=" Checkout ${line:5}"
         echo "$line"
      done || error "Running rsync failed"

# no chroot safeguard, in contrast to the Perl version
cd "$destination" || exit

# iterate through old checkouts, remove obsolete files and directories
if [ -e ".new_checkouts" ]; then
    for oc in "${!old_checkouts[@]}"; do
        if [ ! -f "$oc" ] || (( new_checkouts["$oc"] == 1 )); then continue; fi
        echo " Delete $oc"
	unset old_checkouts["$oc"]
        rm -f "$oc" || warning "Couldn't delete $oc"
    done
    for oc in "${!old_checkouts[@]}"; do
        if [ ! -d "$oc" ] || (( new_checkouts["$oc"] == 1 )); then continue; fi
        echo " Delete $oc"
        rmdir "$oc" || warning "Couldn't delete $oc"
    done
    mv .new_checkouts .checkouts
fi

echo "Finished successfully"
