#! /usr/bin/zsh -feu
# pipefail

unsetopt FUNCTION_ARGZERO


TAB='	'
DRY_RUN=no

usage()
{
    cat <<EOF
usage: ${0##*/} [+-dvh} [--] horizon1 horizon2

 As input it takes 2 'horizon' files.
 Invoke 'git-restate' in each repo project, that is messed-up, i.e.
 diff between horizons.

-d ... just list the diff, no correction is done

EOF
}


compare_horizons()
{
    # 2 files
    # project  ref
    # find which missed in 2nd file, and differences.
    # \s instead of space. not correct.

    # set difference: 1 - 2 by joining by fields 1, 1
    join -t "$TAB" -v 1 \
	-1 1 -2 1 \
	$1 $2  |\
    (
	if test "$DRY_RUN" = yes;
	then
	    cat
	else
# todo:
# inform about projects where git-rebase failed...
# also:  git-rebase bracked by stash/pop possibly.
	    # fixme: failure of `system' won't exit the awk!
	    awk 'BEGIN{exit_code=0}\
/^(.*)\s(.*)\t(.*)$/  {\
result=system(sprintf("git-restate %s %s", $1, $2));\
if (result != 0) { \
   printf "**** git-restate failed in %s: %d\n", $1, result; \
   exit_code=1; \
   next \
   };
}\
/^(.*)\s(.*)\t(.+)$/  {\
result=system(sprintf("cd %s; git stash pop", $1));\
if (result != 0) { printf "**** stash POP failed %d\n", result; exit_code=1}; }\
\
END { exit exit_code}'
	fi
    )
# fixme: currently not idempotent! `stash-pop' w/ no check.

# join -t '\t' -v 1 $1 $2
# join -v 2 $1 $2
# colordiff --unified=1 .$1.br .$2.br
}


while getopts :dh OPT; do
    case $OPT in
	d|+d)
	    DRY_RUN=yes
	    ;;
#	v|+v)
#	    ;;
	h|+h)
	    usage
	    exit
	    ;;
	*)
	    usage
	    exit 2
    esac
done
shift $(( OPTIND - 1 ))
OPTIND=1

if [ $# -lt 2 ]; then
    usage
    exit 1
fi

# not on a ref now:

# different refs:

# equalize-horizon:
compare_horizons $1 $2
