#!/bin/bash -eu
# This script could not report errors via exit status, since
# Make does not consider failure of command in $(shell command)
# expansion fatal.
#
# Instead generate call to Make function 'error'.

fatal () {
	printf '$(error build-alternative: %s)\n' "$*"
	exit 1 # To help debugging.
}
trap 'fatal unknown error, some command failed' EXIT

if ! test -r debian/changelog ; then
	fatal "failed to read debian/changelog"
fi

src=$(dpkg-parsechangelog -SSource); readonly src

have=no
# Diet libc is not present on all architectures, hence the long list of
# architectures in debian/control. Here we just reuse this information.
if dpkg -l dietlibc-dev >/dev/null 2>/dev/null ; then
	have=yes
fi

# I do sure why, but Ubuntu prefer to not support diet libc build. Well,
# let us be nice to them, too.
if dpkg-vendor --derives-from Ubuntu ; then
	have=no
fi

# want means that diet-linked binaries installation is requested.
want=no
IFS=', '
set -- ${DEB_BUILD_PROFILES:-}
for profile ; do
	if test "${profile}" = "pkg.${src}.diet" ; then
		want=yes
		break
	fi
done

if test "${want}" = yes && test "${have}" = no ; then
	fatal "diet libc is not supported on current platform"
fi

cat << EOF
ALT_DIET_HAVE = ${have}
ALT_DIET_WANT = ${want}
EOF

if test "${have}" = yes ; then
	built_using=$(dpkg-query -f'${source:Package} (= ${source:Version})' -W dietlibc-dev)
	printf 'diet:BuiltUsing=%s\n' "${built_using}" >> debian/substvars
fi
trap '' 0

