#! /bin/bash
#
# usage:
#     tag2upload-obtain-origs <setting>=<value> ...
#
#     Writes tag2upload report information to stdout;
#     errors and executed commands to stderr.
#     
# ATTENTION!  This program lives is in the tag2upload builder image,
# but is called by dgit-repos-server on the tag2upload oracle.
# Maintain compatibility and attend to deployment order.
# See dgit-infra-notes-scripts/services-diagram.pdf.
#
# settings:
#
#     v=VERSION-REVISION
#     p=PACKAGE
#     s=SUITE
#     u=UPSTREAM-COMMITID
#
# optional settings:
#
#     bpd                          defaults to ../bpd
#
# Exit status
#
#   Nonretriable errors:
#
#     1     unexpected error in mv, printf, etc.
#           sha256 checksum failed, failed to regenerated required orig
#
#     16    bad configuration or bad arguments (nonretriable error)
#
#     any other (not specially handled)
#
#   Retriable errors:
#
#     75    dgit download-unfetched-origs failed (might be network
#           trouble, or required service unavailable).
#           (EX_TEMPFAIL from sysexits.h)

# We rely on nothing exiting 75 (EX_TEMPFAIL) when it doesn't mean it
set -eu -o pipefail
shopt -s inherit_errexit # #514862, wtf

us="$(basename "$0")"
sharedir="${0%/*}" ###substituted###
. "$sharedir"/dgit-functions.sh

parse-args-settings "$@"

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

set +e
run-dgit download-unfetched-origs			\
	 --write-sha256sums="$s_bpd"/origs.sha256sums
rc=$?
set -e

need_checksums_check=false

case "$rc" in
    0)
	report 'using existing orig(s)'
	exit 0
	;;
    3)
	need_checksums_check=true
	report \
 'some orig(s) not available from archive mirrors, trying to regenerate'
	;;
    4)
	report 'no orig(s) in archive, generating'
	;;
    5)
	report \
'conflicting orig(s) in archive, regenerating, hoping to reproduce a good one'
	;;
    6|8|12)
	fail "unexpected exit status $rc from dgit download-unfetched-origs"
	;;
    *)
	tempfail "failed querying archive for existing orig(s), status $rc"
	;;
esac

# TODO want git-deborig to support bpd
x ${DGIT_DEBORIG_TEST-git deborig} "$s_u"
mv ../"${s_p}_${fversion}.orig".* ../bpd/

report 'created orig'

if $need_checksums_check; then
    if (set -e; cd "$s_bpd"; sha256sum >&2 -c <origs.sha256sums); then
	report 'successfully regenerated orig'
    else
	tempfail 'regenerated orig does not match; hopefully the real orig will become available'
    fi
fi

exit 0
