#include "DLGTick.h"
#include "ivn.h"

#include <link/io.h>

#define NAMELEN 500

BPTR  sout = NULL;

int   Areas = 0;
int   AIndex = -1;

char logstring[1000];
struct GConfig *GCFG;

long __stack =  100000L;

struct Library *DLGBase;

// ------- ======== ---------

void  QuietExit(void);
void  useage(void);
int   GetGCFG(void);
BOOL  ShowBad(BOOL);
int   SendMulti(void);
int   MakeMsg(char *);

// ------- ======== ---------

///   Main
main(int argc, char **argv)
{
   sout = Output();

   DLGBase = OpenLibrary("dlg.library",4L);
   
   if(!DLGBase)
   {
      FPuts(sout,"DLG.library not found!\n");
      QuietExit();
   }

   AFPrintf(NULL,sout,"%s\n",ID_STRING);
   ASPrintf(NULL,logstring,"-> %s",ID_STRING);
   Log(logstring);

   if(argc<2)
      useage();

   if(argc==2)
      if(*argv[1]=='?')
         useage();

   if(!GetGCFG())
   {
      Log(" ! No global config structure");
      AFPrintf(NULL,sout,"DLGTick: No global config structure\n");
      QuietExit();
   }

   Areas = LoadConfig();


   if(Areas == 0)
   {
      AFPrintf(NULL,sout,"No AREAs defined in DLGMail.TIC config file\n");
      Log(" . No areas configured to process");
      QuietExit();
   }

/// Parse args and determine what action to perform
   if(argc>1)
   {

///   TICK
      if(!Stricmp(argv[1],"TICK"))
      {
         if(!Tick(NULL))
//         if(!Tick("inbound"))
         {
            Log(" ! Tick processing failed miserably!");
            AFPrintf(NULL,sout,"** TIC processing failed! **");
         }

      }
//-

///   HATCH
      if(!Stricmp(argv[1],"HATCH"))
      {
         if(!Hatch(argc,argv))
         {
            Log(" ! Hatch processing failed!");
            AFPrintf(NULL,sout,"** HATCH processing failed! **");
         }
      }
//-

///   SHOWBAD
      if(!Stricmp(argv[1],"SHOWBAD"))
      {
         if(!ShowBad(FALSE))
         {
            Log(" ! SHOWBAD processing failed!");
            AFPrintf(NULL,sout,"** SHOWBAD processing failed! **");
         }
      }
//-

///   RESCUE
      if(!Stricmp(argv[1],"RESCUE"))
      {
         if(!ShowBad(TRUE))
         {
            Log(" ! RESCUE processing failed!");
            AFPrintf(NULL,sout,"** RESCUE processing failed! **");
         }
      }
//-

///   PURGE
      if(!Stricmp(argv[1],"PURGE"))
      {
         if(!TickMaint())
         {
            Log(" ! PURGE operation failed!");
            AFPrintf(NULL,sout,"** PURGE operation failed! **");
         }
      }
//-

///   CFG
      if(!Stricmp(argv[1],"CFG"))
      {
         PrintConfig();
      }
//-

      AFPrintf(NULL,sout,"\n\nDLGTick Completed\n");
      QuietExit();
   }
   else
   {
      ASPrintf(NULL,logstring," ! Unknown command line argument: \"%s\"",argv[1]);
      Log(logstring);
      Log("<- DLGTick Terminating\n");
      AFPrintf(NULL,sout,"DLGTick: Unknown argument %s\n",argv[1]);
      QuietExit();
   }
//-

}
//-
///   GetGCFG
GetGCFG()
{
   BPTR fp;
   char stuff[100];

   fp = Open("ENV:GCFG",MODE_OLDFILE);

   if(fp)
   {
      FGets(fp,stuff,20);
      Close(fp);

      GCFG=(struct GConfig *)atoi(stuff);

      if(GCFG==NULL)
      {
         AFPrintf(NULL,sout,"No Global Config - Exiting");
         return(0);
      }

      if((GCFG->MARKER1 != 5551212)||(GCFG->MARKER2 != 5551212))
      {
         AFPrintf(NULL,sout,"Global Config Marker Failure - Exiting\n");
         Log(" ! Global Config Marker Failure");
         return(0);
      }

      if(GCFG) return(1);
   }
   return(0);
}
//-
///   ShowBad
BOOL ShowBad(BOOL Fix)
{
   BOOL  rc = FALSE;

   BPTR  fh;

   char *TicName;
   char  TicPath[500];
   char  Reason[100];
   char  t[1000];
   char *Echo;
   char *Target;
   char  Desc[500];
   char *From;
   char *ThierCRC;
   char *PW;

   struct SearchCookie *sc = NULL;


   if(Fix)
      Log("-> RESCUE");
   else
      Log("-> SHOWBAD");

/// Find files to process
   sc = SearchStart("TICK:BAD","*_TK000000.TIC");

   if(!sc)
   {
      ASPrintf(NULL,logstring," ! Insufficient memory to find TIC files!");
      Log(logstring);
      return(FALSE);
   }

   while(TicName = SearchNext(sc))
   {
      Chk_Abort();

      AFPrintf(NULL,sout,"\n\tProcessing %s\n",TicName);
      ASPrintf(NULL,logstring," . Processing %s",TicName);
      Log(logstring);

      ASPrintf(NULL,TicPath,"Tick:Bad/%s",TicName);
      GetComment(TicPath,Reason);
      AFPrintf(NULL,sout,"\tReason for rejection: %s\n\n",Reason);
      rc = TRUE;

/// Parse tic file
      fh = Open(TicPath,MODE_OLDFILE);

      if(!fh)
      {
         ASPrintf(NULL,logstring," ! Could not open %s!",TicPath);
         Log(logstring);
         return(FALSE);
      }

///   Loop through TIC file and parse it
      while (FGets(fh, t, 999))
      {
         char *par[20];
         char *dup;
         int   c;

         Chk_Abort();
         strcpy(t, stpblk(strtok(t,"\r\n")));
         if(strlen(t) == 0)  continue;         // Skip empty lines
         if(!Strnicmp(t,";",1)) continue;
         dup = strdup(t);
         c = ArgParse(t, par, 19);

///      AREA
         if(!Stricmp(par[0],"AREA"))
         {
            if(c < 2)
            {
               Log(" ! .TIC file syntax error: AREA!");
               AFPrintf(NULL,sout,"\tTic file syntax error: AREA!\n");
               rc = FALSE;
               break;
            }

            Echo = strdup(par[1]);
            continue;
         }
//-

///      FILE
         if(!Stricmp(par[0],"FILE"))
         {
            if(c < 2)
            {
               Log(" ! .TIC file syntax error: FILE!");
               AFPrintf(NULL,sout,"\t.TIC file syntax error: FILE!\n");
               rc = FALSE;
               break;
            }

            Target = strdup(par[1]);
            continue;
         }
//-

///      DESC
         if(!Stricmp(par[0], "DESC"))
         {
            BOOL indesc = FALSE;
            char *d;
            int k;
            int j = 0;

            if(c < 2)
            {
               Log(" ! .TIC file syntax error: DESC!");
               AFPrintf(NULL,sout,"\t.TIC file syntax error: DESC!\n");
               rc = FALSE;
               break;
            }

            d = calloc(1,strlen(dup));

            for(k=4;k<strlen(dup);k++)
            {
               if(indesc)
               {
                  if((dup[k] == '\n')  || (dup[k] == ';') || (dup[k] == '\0') || (dup[k] == '\r'))
                  {
                     d[j] = '\0';
                     break;
                  }

                  d[j] = dup[k];
                  j++;
               }
               else
               {
                  if( isspace(dup[k]))
                  {
                     continue;
                  }
                  else
                  {
                     indesc = TRUE;
                     d[j] = dup[k];
                     j++;
                  }
               }
            }

            strcpy(Desc,d);
            continue;
         }
//-

///      FROM
         if(!Stricmp(par[0],"FROM"))
         {
            if(c < 2)
            {
               Log(" ! .TIC file syntax error: FROM!");
               AFPrintf(NULL,sout,"\t.TIC file syntax error: FROM!\t");
               rc = FALSE;
               break;
            }

            From = strdup(par[1]);
            continue;
         }
//-

///      CRC
      if(!Stricmp(par[0],"CRC"))
      {
         if(c < 2)
         {
            Log(" ! .TIC file syntax error: CRC!");
            AFPrintf(NULL,sout,"\t.TIC file syntax error: CRC!\t");
            rc = FALSE;
            break;
         }

         ThierCRC = strdup(par[1]);
         continue;
      }
//-

///      PW or PASSWORD
      if(!Stricmp(par[0],"PW")   || !Stricmp(par[0],"PASSWORD"))
      {
         if(c < 2)
         {
            Log(" ! .TIC file syntax error: PASSWORD (PW)!");
            AFPrintf(NULL,sout,"\t.TIC file syntax error: PASSWORD (PW)!\n");
            rc = FALSE;
            break;
         }

         PW = strdup(par[1]);
         StripQuote(PW);
         continue;
      }
//-

   }
//-

   if(fh) Close(fh);
//-

/// Error checking for tic file
   if(( rc == FALSE)  || (strlen(Target) == 0))
   {
      Log(" ! Tic file mangled!");
      AFPrintf(NULL,sout,"\tTic file mangled!\n");
      rc = FALSE;
   }
//-

   if(Echo != NULL)
      AFPrintf(NULL,sout,"\t\tEcho: %s\n",Echo);
   else
      AFPrintf(NULL,sout,"\t\tEcho: None Specified\n");

   if(Target != NULL)
      AFPrintf(NULL,sout,"\t\tTarget File: %s\n",Target);
   else
      AFPrintf(NULL,sout,"\t\tTarget File: None Specified!\n");

   if(From != NULL)
      AFPrintf(NULL,sout,"\t\tFrom: %s\n",From);
   else
      AFPrintf(NULL,sout,"\t\tFrom: No address specified!\n");

   if(ThierCRC != NULL)
      AFPrintf(NULL,sout,"\t\tCRC: %s\n",ThierCRC);
   else
      AFPrintf(NULL,sout,"\t\tCRC: None provided!\n");

   if(strlen(Desc) != 0)
      AFPrintf(NULL,sout,"\t\tDescription: \"%s\"\n",Desc);
   else
      AFPrintf(NULL,sout,"\t\tDescription: None provided\n");

   if(PW != NULL)
      AFPrintf(NULL,sout,"\t\tPassword: %s\n",PW);
   else
      AFPrintf(NULL,sout,"\t\tPassword: None provided\n");

/// Attempt to rescue file
   if(Fix)
   {
      DeleteFile("Tick:Bad/TK000001.TIC");
      AFPrintf(NULL,sout,"\tAttempting rescue ... \n\n");

      if(!Stricmp(Reason,"BAD_CRC"))
      {
         AFPrintf(NULL,sout,"\t ****    ALTERING A CRC TO GET A FILE TO PROCESS   ****\n\t **** IS A REALLY STUPID THING TO DO! THIS PROGRAM ****\n\t ****           IS ONLY AS SMART AS YOU ARE!!!     ****\n\t ******************************************************\n\n");
      }

      if(!SmartRename(TicPath,"Tick:Bad/TK000001.TIC"))
      {
         if(!Tick("Tick:Bad/"))
         {
            AFPrintf(NULL,sout,"\tRescue Operation Failed\n\n");
         }
      }
      else
      {
         AFPrintf(NULL,sout,"\tRescue Operation Failed\n\n");
      }
   }
//-

   }

   SearchEnd(sc);
//-

   return(TRUE);
}
//-
///   CheckDLGMAILSTOP()
CheckDLGMAILSTOP()
{
   if(Exists("ENV:DLGMAILSTOP"))
   {
      Log(" * DLGMail told me to stop processing tic files");
      return(1);
   }
   return(0);
}
//-
///   QuietExit()
void QuietExit()
{
   SendMulti();

   DeleteFile(MASTER);
   DelDir("T:TIC_MULTI",NULL);

   Log("<- DLGTick Completed\n");

   if(TicArea) free(TicArea);
   if(DLGBase) CloseLibrary(DLGBase);

   exit(0);
}
//-
///   useage()
void useage()
{
   AFPrintf(NULL,sout,"\n\nUseage: DLGTick <TICK | HATCH | SHOWBAD | RESCUE | PURGE | CFG>\n\n");
   AFPrintf(NULL,sout,"\tIF HATCH you must follow the HATCH argument with:\n");
   AFPrintf(NULL,sout,"\n\t\tFILE \"path:filename\" AREA \"area\" DESC \"description (70 chars max)\"\n");
   AFPrintf(NULL,sout,"\n\tOR you may replace FILE, AREA and DESC keywords and args with\n\n");
   AFPrintf(NULL,sout,"\t\tUSE \"path:filename\" to get FILE, AREA and DESC info from a text file\n\n");

   Log("<- DLGTick Terminating\n");
   QuietExit();
}  
//-
/// SendMulti()
int SendMulti(void)
{
   BPTR fh;
   struct FileInfoBlock *fib;
   char filenames[NAMELEN];
   char *name;
   char token[50];

   *filenames=NULL;

   fib = AllocDosObject(DOS_FIB,NULL);

   if(fib != 0)
   {
      fh=Lock("T:TIC_MULTI",ACCESS_READ);

      if(fh)
      {
         if(Examine(fh,fib))
         {
            while(1)
            {
               if(!ExNext(fh,fib))
                  break;
               else
               {
                  name=fib->fib_FileName;

                  if((strlen(filenames)+strlen(name))<NAMELEN)
                  {
                     strcat(filenames,name);
                     strcat(filenames," ");
                  }
               }
            }
         }
         UnLock(fh);
      }

      FreeDosObject(DOS_FIB,fib);

      if(strlen(filenames))
      {
         name=filenames;

         while(1)
         {
            if(*name==NULL) break;

            name=stptok(name,token,sizeof(token)," ");
            name=stpblk(name);

            /* token is the name we have to process */

            MakeMsg(token);
         }
      }
   }
   return(0);
}
//-
/// MakeMsg()
MakeMsg(char *name)
{
   BPTR in;
   BPTR out;
   int areanum;
   char buffer[510];
   char *s;
   char filename[50];

   strcpy(filename,name);
   areanum=atoi(name);

   DeleteFile(TICKREPLY);

   ASPrintf(NULL,buffer,"T:TIC_MULTI/%s",name);

   if(in = Open(buffer,MODE_OLDFILE))
   {
      if(out = Open(TICKREPLY,MODE_NEWFILE))
      {
         if(areanum)
         {
            AFPrintf(NULL,out,"TO: All\n");
            AFPrintf(NULL,out,"AREA: %d\n",areanum);
            NotateExp(areanum);
         }
         else
         {
            s=filename;
            while(s=strchr(s,'_'))
               *s=' ';

            AFPrintf(NULL,out,"TO: %s\n",filename);
            AFPrintf(NULL,out,"TYPE: P\n");
         }

         AFPrintf(NULL,out,"FROM: DLGTick\n");
         AFPrintf(NULL,out,"SUBJECT: Files processed by DLGTick\n");
         AFPrintf(NULL,out,"BODY:\n");

         if(strlen(TicArea[AIndex].PreList) != 0)
         {
            AFPrintf(NULL,out,"%s\n\n",TicArea[AIndex].PreList);
         }

         while(FGets(in,buffer,500))
            AFPrintf(NULL,out,"%s",buffer);

         if(strlen(TicArea[AIndex].PostList) != 0)
         {
            AFPrintf(NULL,out,"%s\n",TicArea[AIndex].PostList);
         }
         Close(out);
      }
      Close(in);

      ASPrintf(NULL,buffer,"T:TIC_MULTI/%s",name);
      DeleteFile(buffer);

      SendMsg(TICKREPLY);
      DeleteFile(TICKREPLY);
   }
   return(0);
}
//-


