#!/usr/bin/perl

printf("\n\n");

$version="#CFGMAJOR#.#CFGMINOR#.#CFGFIX#";
$ROOT_NAME="Libpkcs11-#CFGDIST#";
$PKG_NAME="libpkcs11-#CFGDIST#";

# Clean old version
printf("Clean old version of fakeroot\n");
`sudo rm -rf ./fakeroot`;
`sudo rm -f ./$PKG_NAME*`;
`mkdir fakeroot`;
`mkdir fakeroot/$ROOT_NAME`;


# Setting the correct ownership
printf("Setting the correct group rights\n");
`sudo chgrp wheel ./fakeroot/$ROOT_NAME`;

# Copying binaries to compiled source
printf("Copying binaries and shared files to compiled source\n");
`sudo cp -R /Library/$ROOT_NAME/lib ./fakeroot/$ROOT_NAME`;
`sudo rm ./fakeroot/$ROOT_NAME/lib/*.la`;
`sudo cp -R ./pkgFiles/* ./fakeroot/$ROOT_NAME/.`;

# Setting the version number in Info.plist
printf("Setting the version number in Info.plist\n");
open(INFO,"Info.plist");
open(BUFFER,">Info.plist.temp");

@filecontent=<INFO>;
$i=0;

while($i <= $#filecontent)
{
	$content=$filecontent[$i];
	
	if($content=~/CFBundleGetInfoString/)
	{
		printf BUFFER $content;
		$content=sprintf("\t\<string\>%s\ Copyright 2006\<\/string\>\n",$version);
		$i++;
	}
	
	if($content=~/CFBundleShortVersionString/)
	{
		printf BUFFER $content;
		$content=sprintf("\t\<string\>%s\<\/string\>\n",$version);
		$i++;
	}

	if($content=~/IFMajorVersion/)
        {
                printf BUFFER $content;
                $content=sprintf("\t\<string\>%s\<\/string\>\n",substr($version,0,1));
                $i++;
        }

	if($content=~/IFMinorVersion/)
        {
                printf BUFFER $content;
                $content=sprintf("\t\<string\>%s\<\/string\>\n",substr($version,2,1));
                $i++;
        }

	print BUFFER $content;
	$i++;
}

close(INFO);
close(BUFFER);

system("rm","Info.plist");
system("mv","Info.plist.temp","Info.plist");

# Executing the packagemaker command
#printf("Analizing the package\n");
#$pkganalize=sprintf("pkgbuild --analyze --root ./fakeroot components.plist");
#printf($pkganalize . "\n");
#system($pkganalize);


# Executing the packagemaker command
printf("Making the package\n");
$packagemaker=sprintf("pkgbuild --component-plist ./components.plist --scripts ./scripts --install-location /Library --info ./Info.plist --identifier %s --root ./fakeroot  %s-%s.pkg",$PKG_NAME, $PKG_NAME, $version);
printf($packagemaker . "\n");
my $err = system($packagemaker);

if($err == 0){
	# Making a volume
	printf("Making the volume\n");
	$hdiutil=sprintf("hdiutil create -verbose -srcfolder %s-%s.pkg -volname \"MultiPkcs11 FNMT %s\" %s-%s.dmg",$PKG_NAME, $version, $version, $PKG_NAME, $version);
	printf($hdiutil . "\n");
	system($hdiutil);
}

`sudo rm -rf ./fakeroot`;
