
#include <setjmp.h>
#include <time.h>
#include <stdlib.h>
#include <FSp_fopen.h>
#include <ctype.h>

#include "ZipGUI.h"				
#include "helpers.h"
#include "macglob.h"

#ifdef HAVE_SYSLOG
#include "syslog.h"
#endif


extern MacZipGlobals	MacZip;
extern Boolean MacUnzip_Noisy;
extern Boolean IgnoreEnvironment;
extern 	jmp_buf EnvForExit;


int CheckLicense(void);
void ZipInitAllVars(void);
int test_expired(int argc, char *argv[], Boolean print);
void Unsupported(char *app);
void ShowAllKeyValues(void);
void PostAppStart(void);



ZipGUI_Globals	g;




int main( void )
{
	DoInitToolbox();				
	DoCheckSysConfig();				
	DoInitGlobals();				
	DoInstallMenus();				
	DoInstallAEHandlers();			
	DoConvertScrap( true );				
	DoEventLoop();					
	
return 0;
} /* main */



OSErr ChooseActionStartCommand(char *CMDString)
{
OSErr  err = 0;

    /* the command line should look like:
       "zip [options] archive *" or  "unzip [options] archive"
       The first word must be either "zip" or "unzip" */     
switch (tolower(CMDString[0]))  {
	case 'z': 
        g.CurrentApp = kZip;   
        strcpy(CMDString,&CMDString[3]);  /*  cut the action 'zip' */
        break;
        
	case 'u':
        g.CurrentApp = kUnzip;
        strcpy(CMDString,&CMDString[5]); /*  cut the action 'unzip' */   
        break;
        
	default:
        g.CurrentApp = kZip;
        printf("\n\n got wrong parameter:  [%s] \n ",CMDString);
        err = paramErr;
        break;
}
    
if (err == 0)
    {  
    g.PathAreOK = true;
    err = StartApp(CMDString, false, NULL);
    }
    
return err;
}




int StartApp(char *cmd, Boolean callFree, char *ZipPath)
{
char		**argvalue;
int 		argc;
char 		buffer[80], *envptr;
Boolean	    NormalReturned = false;
time_t		start_t;
static char *RunTestArchiveCMD = NULL;
Boolean  SysLog_Messages = false;
char        Command[10];

start_t = time(NULL);


#ifdef HAVE_SYSLOG
envptr = getenv("SysLog_Messages");
if (!(envptr == (char *)NULL || *envptr == '\0'))
	{
	if ((stricmp(envptr,"yes") == 0) && (!IgnoreEnvironment))
		{  
		if (g.CurrentApp == kZip) strcpy(Command, "zip");
			else strcpy(Command, "unzip");
		SysLog_Messages = true;
		Print2Syslog(LOG_INFO, "started:     Cmd: [%s %s]", Command, cmd);
		}
	else g.gHasSyslog = false;
	}
#endif


/* check if not already true  */
if (!g.NoWarningBoxes)
	{
	envptr = getenv("NoWarningBoxes");
	if (!(envptr == (char *)NULL || *envptr == '\0'))
		{
		if ((stricmp(envptr,"yes") == 0) && (!IgnoreEnvironment))
			g.NoWarningBoxes = true;
		else 
			g.NoWarningBoxes = false;
		}
	}

Assert_it(cmd,"StartApp cmd == NULL","")
argc = ParseArguments(cmd,&argvalue);

PrepareAppStartup(argc,argvalue);

switch ( g.CurrentApp ) {

	case kZip: 		
		{
		/*
		Since Macintosh users are used to be guided by their
		software in order not to do something stupid, I will
		post an extra warning if the options -m and data fork 
		or similar are both checked.
		*/
		if ((CheckForSwitch("m", argc, argvalue)) &&
			(CheckForSwitch("df", argc, argvalue) || 
			 CheckForSwitch("X", argc, argvalue)  ||
			 CheckForSwitch("e", argc, argvalue)))
			{
			if (g.NoWarningBoxes == false)
				{
	 			if (DoWaringForSwitch()) 
	 				{
	 				g.MaczipIsRunning = false;
					PostAppStart();
	 				return 1;
	 				}
	 			}
			}

		/* Since there is a nasty bug which causes in rare cases
		   invalid entries, we have to warn ..  */
		if (CheckForSwitch("e", argc, argvalue))
			{
			DoAlertUser( CorruptCryptEntries, false );
			}
					
		if (setjmp(EnvForExit) == 0) {			/* the zipmain() starts here */					
			ZipInitAllVars();                   /* there are two possibilities to come back: */
			g.Noisy = !CheckForSwitch("q", argc, argvalue);
			g.is_EnvForExit_valid = true;
			g.ExitResult = zipmain(argc,argvalue);/* 1. the zipmain() returned normaly = no error */
			NormalReturned = true;				/* 2. with longjump() = an error occured */
		}									    /*    zipmain() is exiting with exit() */
												/*    for exit() see printf.c */
		
		g.LastApp = kZip;		
		strcpy(Command, "zip");
		}
    break;								    	

	case kUnzip:	
		{
		if (setjmp(EnvForExit) == 0) 				 
			{						
			g.is_EnvForExit_valid = true;			 
			g.ExitResult = UzpMain(argc,argvalue);
			NormalReturned = true;					 
			}	
		g.LastApp = kUnzip;
		g.Noisy = MacUnzip_Noisy;
		strcpy(Command, "unzip");
		}									 
		break;
		
	default:
		{ 
		printerr("unknown App",-1,g.CurrentApp,__LINE__,__FILE__,""); 
		strcpy(Command, "unknown");
		}
		break;
	}


#ifdef HAVE_SYSLOG
if (SysLog_Messages)
	{
	SysLog_Messages = false;
	Print2Syslog(LOG_INFO, "ended: rc: %d Cmd: [%s %s]", g.ExitResult, Command, cmd);
	Print2Syslog(LOG_INFO, " ");  /* instead: we should flush the buffers here  */
	}
#endif


if (g.SaveMessages)	fclose(g.SaveMessages_fp);

g.AppIsRunning = false;

if (callFree) cmd = StrFree(cmd);

if (g.Noisy)
	{
	if (g.ExitResult == 0) sprintf(buffer,"\n\n Program exiting normally  rc = %d",g.ExitResult);
		else sprintf(buffer,"\n\n Error occurred   rc = %d",g.ExitResult);
	NormalReturned = false;
	PrintMessage(buffer, MessageWindow);		
	sprintf(buffer,"\n time: %4.f sec \n\n\n",difftime(time(NULL), start_t));
	PrintMessage(buffer, MessageWindow);
	ShowAllKeyValues();
	}

if ((g.RunTestArchiveAfterwards) && (g.CurrentApp == kZip) && g.PathAreOK)
	{                                             /* User wants test the Archive */
	g.CurrentApp = kUnzip;                        /* afterwards automatically */
	g.RunTestArchiveAfterwards = false;           /* So I have to start Unzip */
	RunTestArchiveCMD = StrCalloc(CMDLineSize);	  /* with CmdLine: "-t archive.zip" */
	strcpy(RunTestArchiveCMD,"-t ");
	strcat(RunTestArchiveCMD, " \"");	
	Assert_it(ZipPath,"g.archive_path == NULL","") 
	if (ZipPath) 
		{
		strcat(RunTestArchiveCMD,ZipPath);
		strcat(RunTestArchiveCMD, "\" ");	
		ZipPath = StrFree(ZipPath);	
		StartApp(RunTestArchiveCMD, true, NULL);
		}
	}

PostAppStart();

return g.ExitResult;
}





void PrepareAppStartup(int argc,char **argvalue)
{
Str255	itemString;

argc = argc;
argvalue = argvalue;

GetIndString( itemString, rCurrentAppInfo, g.CurrentApp);
strcpy(g.CurrentAppStr,P2CStr(itemString)); 

if (g.SaveMessages)
	g.SaveMessages_fp = FSp_fopen(&g.SaveMessagesFSSpec, "a");
	
g.AppIsRunning = true;

drawStatusLine();

leftStatusString(g.CurrentAppStr);
rightStatusString(".");
IgnoreEnvironment = false;

if (g.RunTestArchiveAfterwards)
	ClearScreen(); 
	
/*  uncomment to timeout a test-version
if (test_expired( argc,argvalue, true) == EXIT_FAILURE) return;
 */
 
if (g.ShowCommandParam) PrintArguments(argc,argvalue);  


g.ExitResult = 0;
g.MaczipIsRunning = true;
DoAdjustMenus();

}




void PostAppStart(void)
{
WindowRef	myWindow;
	
myWindow = FrontWindow();
DoUpdate( myWindow );

g.MaczipIsRunning = false;
DoAdjustMenus();

g.NoWarningBoxes = false;

g.LineBreak = "";
}

