#include <exec/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <exec/ports.h>
#include <exec/memory.h>
#include <libraries/dos.h>
#include <libraries/dosextens.h>
#include <rexx/storage.h>

#include <dlg/globalconfig.h>

#include <link/io.h>

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

struct GConfig *GCFG=NULL;
struct Library *DLGBase = NULL;

#include <proto/exec.h>
#include <proto/dos.h>
#include <proto/dlg.h>
#include <pragmas/dlg.h>

int GetGCFG(void);

static char __RCS__[] = "$VER: KillTD 2.70 ("__DATE__")";

/// SendRexx
LONG  SendRexx(char *port, TEXT *string)
{
   struct RexxMsg *RexxMsg;
   struct RexxArg *ra;

   struct MsgPort *RexxPort;
   struct MsgPort *ReplyPort;
   LONG  retval = 10;

   if (ReplyPort=CreatePort(0,0))
   {
      if(RexxMsg=AllocMem(sizeof(struct RexxMsg), MEMF_CLEAR|MEMF_PUBLIC))
      {
         RexxMsg->rm_Node.mn_ReplyPort=ReplyPort;
         RexxMsg->rm_Node.mn_Length=sizeof(struct RexxMsg);
         RexxMsg->rm_Action=RXCOMM | RXFF_RESULT;
         RexxMsg->rm_Args[0]=string;

         Forbid();
         RexxPort=FindPort(port);
         if (RexxPort)
            PutMsg(RexxPort, (struct Message *) RexxMsg);
         Permit();

         if(RexxPort)
         {
            WaitPort(ReplyPort);
            GetMsg(ReplyPort);
            retval=RexxMsg->rm_Result1;

            if(RexxMsg->rm_Result2)
            {
               ra=(struct RexxArg *)((char *)RexxMsg->rm_Result2 - &( (struct RexxArg *)NULL)->ra_Buff[0]);
               FreeMem(ra, ra->ra_Size);
            }
         }
         FreeMem(RexxMsg,sizeof(struct RexxMsg));
      }
      DeletePort(ReplyPort);
   }
   return retval;
}
//-

/// Main
main(int argc, char *argv[])
{
   char buffer[100];
   LONG  retval;

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

   strcpy(buffer,"TrapDoor");

   if(GetGCFG())
   {
      strcpy(buffer,_TDPORT);

      if(argc>1) strcpy(buffer,argv[1]);

      retval=SendRexx(buffer,"ABORT F");
   }
   
   exit(0);
}
//-

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

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

   if(fp != NULL)
   {
      FGets(fp,stuff,20);
      Close(fp);

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

      if(GCFG==NULL)
      {
         AFPrintf(NULL,Output(),"No Global Config - Exiting. Reboot your system!\n");
         return(0);
      }
      
      if((GCFG->MARKER1 != 5551212)||(GCFG->MARKER2 != 5551212))
      {
         if(_LOG) AFPrintf(NULL,Output(),"Global Config Marker Failure - Exiting. Please reboot!\n");
         return(0);
      }
      
      if(GCFG) return(1);
   }
   return(0);
}
//-
