/* All Rights reserved */

#import <AppKit/AppKit.h>
#import "AppWrapperController.h"
#include <stdio.h>
#include <stdio.h>

@implementation AppWrapperController


- (void) wrap: (id)sender
{
	char	*v_executable = [[executable stringValue] cString],
  			*v_extensions = [[extensions stringValue] cString],
  			*v_appicon = [[appicon stringValue] cString],
  			*v_exticon = [[exticon stringValue] cString],
  			*v_name = [[name stringValue] cString];
	char	v_dir[255],
			v_sys_command[255] = "mkdir ",
			v_file_name[255];
	FILE	*v_file;

	// This belongs in the delegate method for when the app is loaded
    [name setNextText: appicon];
    [appicon setNextText: executable];
    [executable setNextText: extensions];
    [extensions setNextText: exticon];
    [exticon setNextText: name];

	// printf("\n");
	// printf("Application Name = %s\n",v_name);
	// printf("Executable Name = %s\n",v_executable);
	// printf("Extensions = %s\n",v_extensions);
	// printf("Application Icon = %s\n",v_appicon);
	// printf("Ext Icon = %s\n",v_exticon);
	// printf("X Application state is %i\n",[xapp state]);
	// printf("\n");

	// create the wrapper directory
	strcpy(v_dir,v_name);
	strcat(v_dir,".app/");
	strcat(v_sys_command,v_dir);
	// printf("Create Directory Command %s\n",v_sys_command);
	system(v_sys_command);
	strcat(v_sys_command,"Resources");
	// printf("Create Directory Command %s\n",v_sys_command);
	system(v_sys_command);

	// create the shell script
	strcpy(v_file_name,v_dir);
	strcat(v_file_name,v_name);
	v_file = fopen(v_file_name,"w");
	fputs("#!/bin/sh\n",v_file);
	fputs("#",v_file);
	fputs(v_executable,v_file);
	fputs(" $*\n",v_file);
	fputs(v_executable,v_file);
	fputs(" $2 &",v_file);
	fclose(v_file);
	strcpy(v_sys_command,"chmod 755 ");
	strcat(v_sys_command,v_file_name);
	// printf("chmod command %s\n",v_sys_command);
	system(v_sys_command);

	// create the GNUstep info plist file
	strcpy(v_file_name,v_dir);
	strcat(v_file_name,"Resources/Info-gnustep.plist");
	v_file = fopen(v_file_name,"w");
	fputs("{\n",v_file);
	fputs("	NSExecutable = \"",v_file);
	fputs(v_executable,v_file);
	fputs("\";\n",v_file);
	fputs("	NSIcon = \"",v_file);
	fputs(v_appicon,v_file);
	fputs("\";\n",v_file);
	if ([xapp state] == 1) {
		fputs("	XAppWrapper = YES;\n",v_file);
	}
	else
	{
		fputs("XAppWrapper = NO\n",v_file);
	}
	fputs("	NSTypes = (\n",v_file);
	fputs("		{\n",v_file);
	fputs("			NSUnixExtensions = (",v_file);
	fputs(v_extensions,v_file);
	fputs(");\n",v_file);
	fputs("			NSIcon = \"",v_file);
	fputs(v_exticon,v_file);
	fputs("\";\n",v_file);
	fputs("		}\n",v_file);
	fputs("	);\n",v_file);
	fputs("}",v_file);
	fclose(v_file);

	// Tell the user what they have to do now
    // num1 = NSRunAlertPanel(@"OK", @"Hello",
    NSRunAlertPanel(@"OK", @"Hopefully the Wrapper was created.  Now you must copy the new App (./name.app) directory to $GNUSTEP_LOCAL_ROOT/Applications.",
        nil, nil, nil);
}

@end
