########################################################################
#                                                                      #
#              This file is part of the ksh 93u+m package              #
#          Copyright (c) 1984-2012 AT&T Intellectual Property          #
#          Copyright (c) 2020-2024 Contributors to ksh 93u+m           #
#                      and is licensed under the                       #
#                 Eclipse Public License, Version 2.0                  #
#                                                                      #
#                A copy of the License is available at                 #
#      https://www.eclipse.org/org/documents/epl-2.0/EPL-2.0.html      #
#         (with md5 checksum 84283fa8859daf213bdda5a9f8d1be1d)         #
#                                                                      #
#                 Glenn Fowler <gsf@research.att.com>                  #
#                  Martijn Dekker <martijn@inlv.org>                   #
#                                                                      #
########################################################################

# Generator for INIT's *.req library dependency files.
# This script is designed to be called from src/cmd/INIT/Mamfile only.
# It is based on the the code generated by the nmake MAPLIB
# rule from src/cmd/INIT/MAPLIB.mk, and replaces the latter.

# Set options.
case ${ZSH_VERSION+z} in
z)	emulate ksh ;;
*)	(command set -o posix) 2>/dev/null && set -o posix ;;
esac
set -o noglob -o nounset
: $INSTALLROOT	# error out early

# Get colon-separated compiler invocation from arguments.
# Like this whole build system, we assume arguments do not contain
# spaces, or if they do, that they are meant to be field-split.
allcc=
while	test "$#" -gt 0 && test "$1" != ":"
do	allcc=$allcc${allcc:+ }$1
	shift
done
test "${1-}" = ":" || { echo "$0: bad arguments" >&2; exit 1; }
shift

# Get the .req basename.
req=$1
shift
test "${1-}" = ":" || { echo "$0: bad arguments" >&2; exit 1; }
shift

# Get the source file names.
src=
while	test "$#" -gt 0 && test "$1" != ":"
do	src=$src${src:+ }$1
	shift
done
test "${1-}" = ":" || { echo "$0: bad arguments" >&2; exit 1; }
shift

# Get the libraries to test.
libs=
while	test "$#" -gt 0
do	# for each lib name also add '-'
	libs="$libs${libs:+ }$1 -"
	shift
done

# Setup.
trap 'set +o noglob; rm -rf "$req".exe*' 0

######### Main ##########
#  Generate .req file.  #
#########################
r=' -'
for i in $src
do	if	$allcc -c $i >/dev/null 2>&1
	then	rm $(basename $i .c).o &
		g=
		for p in $libs
		do	case $p in
			-)	if	$allcc -o $req.exe $i $g >/dev/null 2>&1
				then	if	! $allcc -o $req.exe $i >/dev/null 2>&1
					then	r=$g
						break 2
					fi
				fi
				g=
				;;
			*)	g="$g -l$p"
				;;
			esac
		done
	fi
done
echo "$r" > $req.req
