#!/usr/bin/perl

if($#ARGV != 0) {
    die "Usage: $0 exefile\n";
}

$exefile = $ARGV[0];

die "Not Regular Exefile: $exefile\n" unless -f $exefile;
die "Not Execute File: $exefile\n" unless -x $exefile;

$appDir = $exefile . '.app';
$contentsDir = $appDir . '/Contents';
$infoListName = $contentsDir . '/Info.plist';
$pkgInfoName = $contentsDir . '/PkgInfo';
$macOsDir = $contentsDir . '/MacOS';
$toCopy = $macOsDir . '/' . $exefile;

if(-d $appDir) {
    if((chmod 0755, $appDir) != 1) {
	die "Directory Permmision Error.\n";
    }
} elsif(mkdir($appDir, 0755) == 0) {
    die "Can't Create Application Directory.\n";
}

if(-d $contentsDir) {
    if((chmod 0755, $contentsDir) != 1) {
	die "Directory Permmision Error.\n";
    }
} elsif(mkdir($contentsDir, 0755) == 0) {
    die "Can't Create Application Directory.\n";
}

if(-d $macOsDir) {
    if((chmod 0755, $macOsDir) != 1) {
	die "Directory Permmision Error.\n";
    }
} elsif(mkdir($macOsDir, 0755) == 0) {
    die "Can't Create Application Directory.\n";
}

open(INFOLIST, "> $infoListName") || die "Can't Open InfoList\n";

select(INFOLIST);

print '<?xml version="1.0" encoding="UTF-8"?>', "\n";
print '<!DOCTYPE plist SYSTEM "file://localhost/System/Library/DTDs/PropertyList.dtd">', "\n";
print '<plist version="0.9">', "\n";
print '<dict>', "\n";
print "\t", '<key>CFBundleIconFile</key>', "\n";
print "\t", '<string></string>', "\n";
print "\t", '<key>CFBundlePackageType</key>', "\n";
print "\t", '<string>APPL</string>', "\n";
print "\t\t", '<key>CFBundleGetInfoString</key>', "\n";
print "\t", '<string>Created by appmake.pl</string>', "\n";
print "\t", '<key>CFBundleSignature</key>', "\n";
print "\t", '<string>????</string>', "\n";
print "\t", '<key>CFBundleExecutable</key>', "\n";
print "\t", '<string>' , $exefile, '</string>', "\n";
print "\t", '<key>NOTE</key>', "\n";
print "\t", '<string>Please, do NOT change this file -- It was generated by appmake.pl.</string>', "\n";
print '</dict>', "\n";
print '</plist>', "\n";

close(INFOLIST);

open(PKGINFO, ">$pkgInfoName") || die "Can't Open PngInfo\n";

print PKGINFO "APPL????\n";
close(PKGINFO);

system("mv $exefile $toCopy");
