#!/usr/bin/perl
#
# gapi-cdecl-insert : Inserts il into an assembly for CDecl callback delegates.
#
# Authors: Mike Kestner <mkestner@novell.com>
#
# Copyright (c) 2005 Novell, Inc.
#
# 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.

die "Usage: gapi-cdecl-insert [--keyfile=<file>] <assembly_path>\n" if ($ARGV > 2);
foreach $arg (@ARGV) {
	if ($arg =~ /--keyfile=(.*)/) {
		$key = $1;
	} elsif (-e $arg) {
		$assembly = $arg;
	} else {
		die "Usage: gapi-cdecl-insert [--keyfile=<file>] <assembly_path>\n";
	}
}

if ($assembly =~ /(.*)\.dll/) {
	$basename = $1;
	`ildasm $assembly /out:$basename.raw`;
	open(INFILE, $basename . ".raw") || die "Couldn't open $basename.raw\n";
	open(OUTFILE, "> $basename.il") || die "Couldn't open $basename.il\n";
	while ($line = <INFILE>) {
		$insert = 1 if ($line =~ /\.custom instance void .*GLib\.CDeclCallbackAttribute/);

		if ($insert && $line =~ /(.*)\s+(Invoke\(.*)/) {
			print OUTFILE "$1 modopt([mscorlib]System.Runtime.CompilerServices.CallConvCdecl) $2";
			$insert = 0;
			next;
		}
		print OUTFILE $line;
	}
	`ilasm /DLL /QUIET $basename.il`;
	`sn -R $assembly gtk-sharp.snk` if ($key);
	unlink "$basename.raw";
	unlink "$basename.il";
	unlink "$basename.res";
} else {
	print "This script only works for dlls.\nUsage: gapi-cdecl-insert [--keyfile=<file>] <dll_path>\n";
}