#! /bin/bash
#
# usage:
#     tag2upload-obtain-origs <setting>=<value> ...
#
#     Writes tag2upload report information to stdout;
#     errors and executed commands to stderr.
#     
# settings:
#
#     v=VERSION-REVISION
#     p=PACKAGE
#     s=SUITE
#     u=UPSTREAM-COMMITID
#
# optional settings:
#
#     bpd                          defaults to ../bpd

set -eu -o pipefail
shopt -s inherit_errexit # #514862, wtf

fail () { echo >&2 "tag2upload-obtain-origs: error: $*"; exit 16; }
x () { echo >&2 "+ $*"; "$@"; }

s_bpd=../bpd

while [ $# != 0 ]; do
    case "$1" in
	--*) fail "unknown option" ;;
	*=*)
	    k="${1%%=*}"
	    v="${1#*=}"
	    case "$k" in
		*[^0-9a-z-]*) fail "bad syntax for setting" ;;
		*)
		    eval "s_$k=\$v"
		    ;;
	    esac
	    shift
	    ;;
	*) fail "non-option arguments must all be settings K=V" ;;
    esac
done

: ${DGIT_DRS_DGIT:=dgit}
run-dgit () {
    x $DGIT_DRS_DGIT --build-products-dir="$s_bpd" -p"$s_p" "$@" >&2
}
report () {
    printf "%s\n" "$*"
    printf >&2 "# %s\n" "$*"
}

set +e
run-dgit --for-push fetch "$s_s"
rc=$?
set -e

case "$rc" in
    0) report 'fetched existing package from archive and/or dgit-repos' ;;
    4) report 'package is new in this suite' ;;
    *) fail "dgit fetch failed" ;;
esac

uversion="${s_v%-*}" # strip revision
fversion="${uversion#*:}" # strip epoch

origs=$(
    find "$s_bpd" -name "${s_p}_${fversion}.orig.*"
)
if [ "x$origs" != x ]; then
    report 'using existing orig(s)'
    exit 0
fi

set +e
run-dgit download-unfetched-origs
rc=$?
set -e

case "$rc" in
    0)
	report 'using orig(s) downloaded from archive'
	exit 0
	;;
    4)
	report 'no orig(s) in archive, generating'
	;;
    5)
	report \
'conflicting orig(s) in archive, regenerating, hoping to reproduce a good one'
	;;
    *)
	fail 'failed querying archive for existing orig(s)'
	;;
esac

x git deborig "$s_u"

report 'created orig'

exit 0
