#!/bin/sh
#-------------------------------------------------------------------------------
# Phorward C/C++ Library
# Copyright (C) 2006-2019 by Phorward Software Technologies, Jan Max Meyer
# https://phorward.info ++ contact<at>phorward<dash>software<dot>com
# All rights reserved. See LICENSE for more information.
#
# Script:		pinclude
# Author:		Jan Max Meyer
# Usage:		Local include resolver
#-------------------------------------------------------------------------------

. .phorward >/dev/null

help()
{
	echo "Usage: `basename $0` OPTIONS file..."
	echo
	echo "    -b  --begin     STRING   Configure block comment begin to STRING ($cbeg)"
	echo "    -e  --end       STRING   Configure block comment end to STRING ($cend)"
	echo "    -h  --help               Show this help, and exit."
	echo "    -l  --line      STRING   Configure line comment begin to STRING ($cline)"
	echo "    -q  --quiet              Disable commented output"
	echo "    -V  --version            Show version info and exit."
	echo
}

#assemble options
quiet=1
cbeg="/*"
cend="*/"
cline=""

while [ "$1" ]
do
	case "$1" in
		-b|--begin)
			cbeg=$2
			shift
			;;
		-e|--end)
			cend=$2
			shift
			;;
		-h|--help)
		    help
		    exit 0
		    ;;
		-l|--line)
			cline=$2
			shift
			;;
		-q|--quiet)
			quiet=0
			;;
		-V|--version)
		    version `basename $0` "Local include resolver"
		    exit 0
		    ;;
		*)
			break
			;;
	esac

	shift
done

if [ $# -lt 1 ]
then
	help
	exit 1
fi


if [ $quiet -ne 0 ]
then
	if [ "$cbeg" != "" ]
	then
		echo "$cbeg"
	fi

	echo "$cline	This file was automatically generated by `basename $0`."
	echo "$cline	DO NOT CHANGE THIS FILE MANUALLY. IT WILL GO AWAY!"

	if [ "$cend" != "" ]
	then
		echo "$cend"
	fi
fi

while [ "$1" != "" ]
do
	awk -vcomments=$quiet -vcbeg="$cbeg" -vcend="$cend" -vcline="$cline" '

BEGIN				{	FS = "[ \t\"]+"		}

/##include[ \t]+\"/	{
						if( !system( "test -f " $2 ) )
						{
							if( !comments )
								print cbeg cline " BEGIN $2 " cend

							system( "cat " $2 )

							if( comments )
								print cbeg cline " END $2 " cend
						}
						else
						{
							print "pinclude: File not found: " $2
							exit 1
						}
						next
					}

/##exec/			{
						gsub( /##exec/, "" )

						if( comments )
							print cbeg cline " BEGIN $0 " cend

						system( $0 )

						if( comments )
							print cbeg cline " END $0 " cend

						next
					}

					{
						print
					}
	' $1 | remove_c_comments

	if [ $? -ne 0 ]
	then
		exit 1
	fi

	shift
done

