/* Bug - if a request comes in like "+ tagname" then
 * things go haywire */

#include "DLGAreaFix.h"

#include <link/io.h>

long __stack = 50000L;

struct Library     *IntuitionBase = 0;
struct Library     *DLGBase = 0;

struct TicStruct   *TS = NULL;

BPTR  sout = NULL;

struct GConfig     *GCFG;
char  logstring[2000];

struct areas  *a;         /* ross's reference */

#include <private/Version.h>
#define  ObjRev "1"
const UBYTE version[]="\0$VER: DLGAreaFix " BUILDVER "." ObjRev " ©" COPYRIGHT " by Digerati Dreams "__AMIGADATE__;
static char ID_STRING[] = "DLGAreaFix " BUILDVER " ©" COPYRIGHT " by Digerati Dreams " __AMIGADATE__;

int               SomeReport(int, char **);
void              QuietExit(void);
int               GetGCFG(void);
void              template(void);

/// Main
main(int argc, char **argv)
{
   int   num;

   sout = Output();

   DLGBase = OpenLibrary("dlg.library", 0L);

   if (!DLGBase)
   {
      CloseLibrary(IntuitionBase);
      FPuts(sout,"Couldn't open DLG library\n");
      exit(20);
   }

   if ((argc < 2) || (*argv[1] == '?'))
   {
      template();
      exit(0);
   }

   IntuitionBase = OpenLibrary("intuition.library", 0L);

   if (!IntuitionBase)
   {
      AFPrintf(NULL,sout,"Couldn't open Intuition\n");
      exit(20);
   }

   num = atoi(argv[1]);

   if (!GetGCFG())
   {
      AFPrintf(NULL,sout,"No DLG global config structure - DLGMail must be running before\n");
      AFPrintf(NULL,sout,"DLGAreaFix will work...\n");
      exit(20);
   }

   _RETURNCODE = 0;

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

   a = _ROSSAREAS;
   Log(".  Loading DLGMail.TIC file");
   LoadDLGMAILTIC();

   if (!a)
   {
      Log("!  ERROR FOUND IN DLGMail.ARE FILE");
      AFPrintf(NULL,sout,"ERROR FOUND IN DLGMail.ARE FILE\n");
      _RETURNCODE = 0;
      QuietExit();
   }

   EnterArea(_NETMAILDIR, MSGLOCK);

   if (num)
   {
      AreaFix(num);
   }
   else
   {
      if (!Stricmp(argv[1], "STATUS") || !Stricmp(argv[1], "REPORT"))
      {
         AFPrintf(NULL,sout,"Generating reports...\n\n");

         if (a)
         {
            SomeReport(argc, argv);
         }
         else
         {
            AFPrintf(NULL,sout,"Areas structure not loaded - no report can be generated\n");
         }
      }
      else
      {
         if (!Stricmp(argv[1], "DEADEND"))
         {
            AFPrintf(NULL,sout,"Processing dead-end passthrough area disconnections...\n");
            DeadEnd(argc, argv);
         }
         else
         {
            AFPrintf(NULL,sout,"Command line option error. Run program with no args for template\n");
         }
      }
   }

   QuietExit();
}
//-

/// SomeReport
SomeReport(int argc, char **argv)
{
   char *r;
   char  outputfile[100];
   char  address[100];
   char  sysop[100];
   int   rc;
   char  buffer[200];
   char  token[100];
   BPTR  fh;

   if (argc > 2)
   {
      if (!Stricmp(argv[1], "REPORT") && argc > 4)
      {
         AFPrintf(NULL,sout,"Generating a local or netmail connection report for a single node:\n");
         strncpy(address, argv[3], 99);
         address[99] = 0;
         
         if (Make5DAddress(sysop, address))
         {
            AFPrintf(NULL,sout,"     Generating a report for %s @ %s\n", sysop, address);

            if (Stricmp(argv[4], "NETMAIL"))
            {
               strcpy(outputfile, argv[4]);
            }
            else
            {
               strcpy(outputfile, "T:NODE.RPT");
            }

            if (*argv[2] == 'm' || *argv[2] == 'M')
               rc = GenerateActiveReport(outputfile, address);

            if (rc && !Stricmp(argv[4], "NETMAIL"))
            {
               r = strchr(address, '!');

               if (r)
               {
                  r++;

                  ASPrintf(NULL,buffer, "DLG:SendMsg -n -q -f \"DLGAreaFix\" -s \"Connection Report\" -b \"T:NODE.RPT\" -r \"NET %s %s\"", r, sysop);

                  if (TestPCAddress(address))
                     rc = Spawn(Input(),sout, buffer);
                  else
                     Log(".  Message not sent - Message was to Planet Connect");
               }
            }
         }
         else
         {
            AFPrintf(NULL,sout,"No SYSOP entry in .AFX file for %s\n", address);
         }
      }

      if (!Stricmp(argv[1], "STATUS") && argc > 2)
      {
         AFPrintf(NULL,sout,"Generating multiple connection reports:\n");

         if (fh = Open("FIDO:DLGMAIL.AFX", MODE_OLDFILE))
         {
            while (FGets(fh, buffer, sizeof(buffer)))
            {
               if (*buffer == ';')
                  continue;

               r = buffer;
               r = stpblk(r);
               r = mystpsym(r, token, sizeof(token));

               if (Stricmp(token, "sysop"))
                  continue;

              /* found a sysop line */

               r = stpblk(r);
               r = mystpsym(r, sysop, sizeof(sysop));
               r = stpblk(r);
               r = mystpsym(r, token, sizeof(token));
               
               if (Stricmp(token, "address"))
                  continue;
               
               r = stpblk(r);
               r = mystpsym(r, address, sizeof(address));
               r = stpblk(r);
               r = mystpsym(r, token, sizeof(token));
               
               if (!Stricmp(token, "useaddress"))
               {
                  r = stpblk(r);
                  r = mystpsym(r, address, sizeof(address));
               }

               AFPrintf(NULL,sout,"     Generating a report for %s @ %s\n", sysop, address);

               DeleteFile("T:NODE.RPT");
               strcpy(outputfile, "T:NODE.RPT");

               if (*argv[2] == 'm' || *argv[2] == 'M')
                  rc = GenerateActiveReport(outputfile, address);

               r = strchr(address, '!');
   
               if (r)
               {
                  r++;
                  ASPrintf(NULL,buffer, "DLG:SendMsg -n -q -f \"DLGAreaFix\" -s \"Connection Report\" -b \"T:NODE.RPT\" -r \"NET %s %s\"", r, sysop);

                  if (TestPCAddress(address))
                     rc = Spawn(Input(),sout, buffer);
                  else
                     Log(".  Message not sent - Message was to Planet Connect");
               }
            }
            Close(fh);
         }
         else
         {
            AFPrintf(NULL,sout,"Couldn't open FIDO:DLGMail.AFX file for read - no status messages sent\n");
         }
      }
   }

   return (rc);
}
//-

/// QuietExit
void QuietExit()
{
   LeaveArea(_NETMAILDIR, MSGLOCK);

#ifndef NEWROSSAREAS
   if (a)
      delete_areas(a);                 /* ross code */
#endif

   Log("<- AreaFix ending...\n");

   _RETURNCODE = ACT_DLGNET;

   if (IntuitionBase)
      CloseLibrary(IntuitionBase);

   if (DLGBase)
      CloseLibrary(DLGBase);

   exit(0);
}
//-

/// GetCGFG
GetGCFG()
{
   BPTR  fh;
   char  stuff[100];

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

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

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

      if (GCFG == NULL)
      {
         AFPrintf(NULL,sout,"No GCFG - Exiting\n");
         exit(20);
      }

      if ((GCFG->MARKER1 != 5551212) || (GCFG->MARKER2 != 5551212))
      {
         AFPrintf(NULL,sout,"GCFG Marker Failure - Exiting\n");
         exit(20);
      }

      if (GCFG)
         return (1);
   }
   return (0);
}
//-

/* for normal areafix operation, arguments look like this:
 * DLGAreaFix 319 (where 319 is the netmail message number to parse)
 *
 * for report operation, arguments look like this: 
 * DLGAreaFix REPORT < M | F > < partialaddress > < NETMAIL | outputfile >
 */

/// template
void template(void)
{
   AFPrintf(NULL,sout,"%s\n\n", ID_STRING);

   AFPrintf(NULL,sout,"Useage: DLGAreaFix called from within DLGMail processes Areafix and Raid\n");
   AFPrintf(NULL,sout,"        request messages, connects and disconnects areas, and creates\n");
   AFPrintf(NULL,sout,"        reply reports.\n\n");

   AFPrintf(NULL,sout,"        DLGAreaFix REPORT < M | F > <address> < NETMAIL | filename>\n");
   AFPrintf(NULL,sout,"        generates a connection report for <address> and either\n");
   AFPrintf(NULL,sout,"        NETMAILs it to <address> or saves it locally to <filename>.\n");
   AFPrintf(NULL,sout,"        Specify M for messages, F for files (files not implemented yet).\n\n");

   AFPrintf(NULL,sout,"        DLGAreaFix STATUS < M | F> generates a report for all nodes as\n");
   AFPrintf(NULL,sout,"        listed in the DLGMAIL.AFX file configured for being SYSOP.\n");
   AFPrintf(NULL,sout,"        These reports are netmailed to each sysop.\n\n");

   AFPrintf(NULL,sout,"        DEADEND useage:\n\n");
   AFPrintf(NULL,sout,"          DLGAreaFix DEADEND <5DAddress> <filename>\n\n");
   AFPrintf(NULL,sout,"             Generates report of deadend areas.\n\n");
   AFPrintf(NULL,sout,"          DLGAreaFix DEADEND <5DAddress> DISCONNECT\n\n");
   AFPrintf(NULL,sout,"             Auto-disconnects you from deadend echos.\n");
}
//-

