#!/bin/sh
#
# gapi-cdecl-insert : Inserts il into an assembly for CDecl callback delegates.
#
# Author: Christian Hoff <christian_hoff@gmx.net>
#
# Copyright (c) 2005 Novell, Inc.
# Copyright (c) 2009 Christian Hoff
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of version 2 of the GNU General Public
# License as published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public
# License along with this program; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place - Suite 330,
# Boston, MA 02111-1307, USA.

usage="Usage: gapi-cdecl-insert [--keyfile=<file>] <assembly_path>";
while [ $1 ]; do
	arg=`expr "$1" : '--keyfile=\(.*\)'`
	if [ $? -eq 0 ]; then # check whether "expr" has returned an error code
		if [ -z $keyfile ]; then
			keyfile=$arg
		else
			echo -e "--keyfile option cannot be defined multiple times\n${usage}"
		fi
	else
		if [ -z $assembly ]; then
			assembly=$1
		else
			echo -e "Only one input file allowed\n${usage}"
			exit 1
		fi
	fi
	shift # Replaces $1 with next param
done
if [ -n "$keyfile" -a ! -r "$keyfile" ]; then
	echo -e "${0}: ERROR: Assembly key file \"$keyfile\" does not exist"
	exit 2
fi
if [ ! -r "$assembly" ]; then
	echo -e "${0}: ERROR: Assembly \"$assembly\" does not exist"
	exit 3
fi

echo -e "${0}: Executing ildasm"
echo `ildasm ${assembly} /out:${assembly}.raw`

echo -e "${0}: Parsing generated IL"
sed 's/^[ \t]*\.custom instance void .*GLib\.CDeclCallbackAttribute::\.ctor.*$/.custom instance void [mscorlib]System\.Runtime\.InteropServices\.UnmanagedFunctionPointerAttribute::\.ctor\(valuetype [mscorlib]System\.Runtime\.InteropServices\.CallingConvention\) = \( 01 00 02 00 00 00 00 00 \) /' < ${assembly}.raw > ${assembly}.il

rm "$assembly"
echo -e "${0}: Executing ilasm"
if [ -z $keyfile ]; then
	echo `ilasm /quiet /dll /output=${assembly} /resource=${assembly}.res ${assembly}.il`
else
	echo `ilasm /quiet /dll /output=${assembly} /resource=${assembly}.res /key=${keyfile} ${assembly}.il`
fi
rm "${assembly}.raw"
rm "${assembly}.il"
rm "${assembly}.res"