
##################################################################
# substitute
##################################################################
function uc_build_sed_script {

	local VARNAME

	__uc_sed_script="$__uc_scriptdir/sedscript"
	if [ ! -f "$__uc_sed_script" ]; then
		# Support reproducible builds
		if [ -n "$SOURCE_DATE_EPOCH" ]; then
			uc_date="$(date -u -d @$SOURCE_DATE_EPOCH +'%B %-e, %Y')"
		else
			uc_date="$(date +'%B %-e, %Y')"
		fi

		for varname in $(set | sed '/^uc_\(.*\)=.*/!d;s//\1/'); do
			VARNAME=$(echo $varname | tr a-z A-Z)
			echo "s|@$VARNAME@|$(eval echo \$uc_$varname)|"
		done >$__uc_sed_script
	fi

	echo "$__uc_sed_script"
}

function uc_subst {

	local sedfile=$(uc_build_sed_script)

	for output; do
		input="$output.in"

		if [ ! -f "$input" ]; then
			echo "Cannot find input file $input" >&2
			exit 2
		fi

		echo -n "Generating $output... "

		sed -f $sedfile <$input >$output.tmp
		if test -f $output && cmp -s $output $output.tmp; then
			echo "unchanged"
			rm -f $output.tmp
		else
			mv $output.tmp $output
			echo "done"
		fi
		chmod --reference=$input $output
	done
}

if [ $(basename $0) = "subst" ]; then
	__uc_scriptdir="$(dirname $0)"
	uc_subst "$@"
elif [ "$__uc_rechecking" = true ]; then
	# The user is running ./configure which is possibly changing
	# some settings. We have to rebuild the sed script
	rm -f "$__uc_scriptdir/sedscript"
fi
