#!/bin/sh

gencommon () {
	lint="build/${path}/${s%.*}${1}.l"
	dep="build/${path}/${s%.*}${1}.d"
	obj="build/${path}/${s%.*}${1}"

	echo "${dep}:"		>> deps.mk
	echo "-include ${dep}"	>> deps.mk
	echo "${obj}: ${s}"		>> deps.mk
}

genlink () {
	gencommon ".ld"
	if [ ${kern} ]; then
		echo "	\$(GENLINK) ${s} | \$(STRIPLINK) > ${obj}" >> deps.mk
	else
		echo "	\$(GENLINK) ${s} | \$(STRIPLINK) | \$(KERN_INFO) > ${obj}" >> deps.mk;
	fi
}

genrule () {
	gencommon "${1}"
	echo "	\$(COMPILE) ${flags} -c ${s} -o ${obj}"	>> deps.mk

	echo "${lint}: ${s}"			>> deps.mk
	echo "	\$(LINT) ${flags} -c ${s} -o /dev/null"	>> deps.mk
}

case "${1}" in
	--kernel)
		kern=1
		path=kernel
		flags='$(KERN_FLAGS)'
		;;
	--init)
		path=init
		flags='$(INIT_FLAGS)'
		;;
esac

case "${2}" in
	--compile)
		suffix=.o
		func=genrule
		;;
	--link)
		suffix=.ld
		func=genlink
esac

# create all subdirectories
mkdir -p $(echo "${3}" | xargs -n 1 dirname | uniq | sed 's|^|build/init/|g')
mkdir -p $(echo "${3}" | xargs -n 1 dirname | uniq | sed 's|^|build/kernel/|g')

for s in ${3}
do
	${func} ${suffix}
	echo ${obj}
done
