#! /bin/bash

show_help()
{
    echo "sync-quilt [-h|--help] [-r|--reverse] [-v|--verbose]"
    echo
    exit
}

files_to_copy()
{
    quilt files
}

opt_verbose=0
opt_reverse=0

while [ $# -gt 0 ]
do
    case $1 in
	--help|-h)
	    show_help
	    ;;
	--verbose|-v)
	    opt_verbose=1
	    ;;
	--reverse|-r)
	    opt_reverse=1
	    ;;
	*)
	    echo "Unknown option $1"
	    exit 2
	    ;;
    esac
    shift
done

# host=$(git config --local --get sync.host)
# path=$(git config --local --get sync.path)
# rsync=$(git config --local --get sync.rsync)
host=root@luonnotar
path=/usr/lib/python3/dist-packages

if [ -z "$host" -o  -z "$path" ]
then
    show_help
fi

# while [ ! -d .git ]
# do
#     cd ..
#     if [ "$(pwd)" = "/" ]
#     then
# 	echo "No repository found"
# 	exit 4
#     fi
# done
cd /tmp/work/moin-1.9.11

if [ "$rsync" = "true" ]
then
    if [ $opt_verbose -eq 0 ]
    then
	verbosity=
    else
	verbosity=-v
    fi

    if [ $opt_reverse -eq 0 ]
    then
	for f in $(files_to_copy)
	do
	    rsync ${verbosity} -a ${f} ${host}:${path}/${f}
	done
    else
	for f in $(files_to_copy)
	do
	    rsync ${verbosity} -a ${host}:${path}/${f} ${f}
	done
    fi
else
    if [ $opt_verbose -eq 0 ]
    then
	verbosity=--quiet
    else
	verbosity=--verbose
    fi

    if [ $opt_reverse -eq 0 ]
    then
	files_to_copy \
	    | cpio ${verbosity} -o | bzip2 | ssh ${host} "(cd ${path} && bunzip2 | cpio --unconditional --quiet -i -d)" 2> /dev/null
    else
	files_to_copy \
	    | ssh ${host} "(cd ${path} && cpio ${verbosity} -o | bzip2 )" \
	    | bunzip2 | cpio --quiet --unconditional -i 2>&1
    fi
fi

if [ $? -ne 0 ]
then
    echo "Error $?" > /dev/stderr
    exit $?
fi
