//
//  main.m
//  Test1
//
//  Created by Administrateur on 05.05.11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

// Max arg on command line
#define MAX_ARG 100
// Nb max of characters for an argument
#define MAX_ARG_LENGTH 1024
//Maximum size of the string containing the command to be executed.
//This size is the maximum of argument times the max number of arguments times
//2 to allow each characters of the string to be quoted.
#define CMD_LINE_SIZE (MAX_ARG*MAX_ARG_LENGTH*2)
//Name of the programme doining the job
#define REAL_PROGRAM "libexec/EasyQuantis"

#include <unistd.h>
#include <stdlib.h>


#import <Cocoa/Cocoa.h>

/* The following function quotes all the Shell
   specific characters in the string passed in parameter.
   The space should be sufficient to allow the quote character.
 
   The function has 1 parameter
      1) The string to be quoted
 
   The function return the address of the quoted string.
 */

char * quoteShell(char * cmd){
	int currPos=0,newCurrPos=0;
	char currCar; 
	char newCmd[CMD_LINE_SIZE];
	
	while(currPos<CMD_LINE_SIZE && (currCar=cmd[currPos]) != '\0'){
		switch (currCar) {
			case ' ':
			case '\'':
			case '*':
			case '?':
			case '"':
			case '(':
			case ')':
			case ':':
			case '<':
			case '>':
			case '|':
			case '&':
			case ';':
			case '$':
			case '`':
			case '!':
			case '\t':
			case '\n':
			case '\\':
				newCmd[newCurrPos]='\\';
				newCurrPos++;
				break;
			default:
				break;
		}
		newCmd[newCurrPos]=currCar;
		newCurrPos++;currPos++;
	}
	newCmd[newCurrPos]='\0';
	strcpy(cmd,newCmd);
	return cmd;
}

int NSApplicationMain(int argc,  const char ** argv){
	char cmd[CMD_LINE_SIZE];
	char * pos;
	
	strlcpy(cmd,argv[0],MAX_ARG_LENGTH);
	pos=strstr(cmd,"/Contents");
	if (pos != NULL){
        // end the cmd at the last character '/'
		*pos='\0';
		strcat(cmd,"/Contents/");
		strcat(cmd,REAL_PROGRAM);
    }
	else{
		strcpy(cmd,REAL_PROGRAM);
	}   
	return system(quoteShell(cmd));	
}

int main(int argc, char *argv[])
{
    return NSApplicationMain(argc,  (const char **) argv);
}
