#!/usr/bin/perl -w

my $srcdir=$ARGV[0];
my $srcpath=$ARGV[1];
my $name=$ARGV[2];
my $dirref=$ARGV[3];
my $diskid=$ARGV[4];
my $to=$ARGV[5];

my $component = 1000;
my $indent = 3;
my $first = 1;
#my $buildroot = $ENV{'BUILDROOT'};

#print STDERR join(" ", "Got args:", @ARGV, "\n");

my @components;
sub do_it {
	my ($path) = @_;
	my $f = $path;
	$f =~ s/.*\\//;
	my $ind = ' ' x (2 * $indent);
	if (-d $path) {
		my $p = $path;
		#$p =~ s/\Q$buildroot/\$(var.BuildRoot)/g;
		$p =~ s/\Q$srcdir/\$(var.$to)/g;
		++$component;
		if ($first) {
			print "$ind<Directory Id='${name}_${component}' Name='$name' FileSource='$p'>\n";
			$first = 0;
		} else {
			print "$ind<Directory Id='${name}_${component}' Name='$f' FileSource='$p'>\n";
			print "$ind  <Component Id='${name}_${component}' Guid='{E88B9843-688B-00${diskid}-3333-E137EAA1$component}'>\n";
			print "$ind    <CreateFolder/>\n";
			print "$ind  </Component>\n";
			push @components,  "      <ComponentRef Id='${name}_${component}'/>\n";
		}
		++$indent;
		opendir DIRH, $path or die("couldn't open $path: $!");
		my @files = grep { $_ ne '.' and $_ ne '..'  and $_ ne '.svn'} readdir DIRH;
		closedir DIRH;
		foreach $file (@files) {
			#$file =~ s/\&/\&amp;/g;
			do_it("$path\\$file");
		}
		--$indent;
		print "$ind</Directory>\n";
	}
	else {
		++$component;
		print "$ind<Component Id='${name}_${component}' Win64='\$(var.Win64YesNo)' Guid='*' DiskId='$diskid'>\n";
		print "$ind  <File Id='${name}_${component}' Name='$f'/>\n";
		print "$ind</Component>\n";
		push @components,  "      <ComponentRef Id='${name}_${component}'/>\n";
	}
}


print "<?xml version='1.0' encoding='ascii' ?>\n\n";
#print "<?include includes.wxi ?>\n\n";
print "<Wix xmlns='http://schemas.microsoft.com/wix/2006/wi'>\n";
print "  <Fragment>\n";
print "    <DirectoryRef Id='$dirref'>\n";
do_it "$srcdir\\$srcpath";
print "    </DirectoryRef>\n";
print "    <ComponentGroup Id='$name'>\n";
print foreach @components;
print "    </ComponentGroup>\n";
print "  </Fragment>\n";
print "</Wix>\n";

exit 0;
