#!/bin/sh

gen_asm() {
	in=$1
	codesout=$2
	codesinc=`echo $2 | sed -e 's/.*include\///g'`
	protosout=$3
	asmout=$4
	asmcommon=`echo $5 | sed -e 's/.*include\///g'`
	prototypes=`echo $6 | sed -e 's/.*include\///g'`

	codesdef=`echo $codesout | sed -e 's/.*include\///g' | tr "[[:space:]].-" _`
	protosdef=`echo $protosout | sed -e 's/.*include\///g' | tr "[[:space:]].-" _`

	echo "/* Autogenerated, don't edit */"	>  $codesout
	echo "#ifndef $codesdef"		>> $codesout
	echo "#define $codesdef"		>> $codesout

	echo "/* Autogenerated, don't edit */"	>  $protosout
	echo "#ifndef $protosdef"		>> $protosout
	echo "#define $protosdef"		>> $protosout
	echo "#ifndef CR_NOGLIBC"		>> $protosout
	echo "#error This file should only be used in the parasite code" >> $protosout
	echo "#endif"				>> $protosout
	echo "#include \"$prototypes\""		>> $protosout
	echo "#include \"$codesinc\""		>> $protosout

	echo "/* Autogenerated, don't edit */"	>  $asmout
	echo "#include \"$codesinc\""		>> $asmout
	echo "#include \"$asmcommon\""		>> $asmout

	cat $in | egrep -v '^#' | sed -e 's/\t\{1,\}/|/g' | awk -F '|' '{print "#define", $1, $2}'		>> $codesout
	cat $in | egrep -v '^#' | sed -e 's/\t\{1,\}/|/g' | awk -F '|' '{print "extern long ", $3, $4, ";"}'	>> $protosout
	cat $in | egrep -v '^#' | sed -e 's/\t\{1,\}/|/g' | awk -F '|' '{print "SYSCALL(", $3, ",", $2, ")"}'	>> $asmout

	echo "#endif /* $codesdef */"		>> $codesout
	echo "#endif /* $protosdef */"		>> $protosout
}

gen_exec() {
	in=$1
	codecout=$2

	echo "/* Autogenerated, don't edit */"	>  $codecout

	cat $in | egrep -v '^#' | sed -e 's/\t\{1,\}/|/g' | awk -F '|' '{print "SYSCALL(", substr($3, 5), ",", $2, ")"}' >> $codecout
}

if [ "$1" = "--asm" ]; then
	shift
	gen_asm $@
fi

if [ "$1" = "--exec" ]; then
	shift
	gen_exec $@
fi
