#include "dlghub.h"
#include "ivn.h"

#include <link/io.h>

char logstring[1000];

int DAY;
int DATE;
int YEAR;
int MONTH;
int HOUR;
int MIN;
char DATESTR[20];
char TIMESTR[20];
char DATETIMESTR[40];

struct GConfig *GCFG;
struct StoredCommands *CURCMDS=NULL;

struct Library *DLGBase;

BPTR sout;

BOOL DEBUG = FALSE;
BOOL DO_LOG = FALSE;
BOOL CHAT = FALSE;

int  Index = 0;

long __stack = 50000L;

/* ======================= */

void          GetClk(void);
int           GetGCFG(void);

/* ======================= */

/// Main
int main(int argc, char **argv)
{
   sout = Output();
   
   DLGBase = OpenLibrary("dlg.library",2L);
   
   if(!DLGBase)
   {
      FPuts(sout,"DLG.library not found!\n");
      exit(50);
   }

   GetGCFG();

   if(_LOG && _NLHUB) DO_LOG = TRUE;
   if(_NLHUB) DO_LOG = TRUE;
   
   if(_MASTERDEBUG) DEBUG = TRUE;
   if(_MyDEBUG) DEBUG = TRUE;
   if(_DLGHUB_DB) DEBUG = TRUE;
   
   if(_LOG) CHAT = TRUE;
   if(_VERBOSITY > _LOG) CHAT = TRUE;
   if((_SHOWHUB > _VERBOSITY) && (_SHOWHUB > _LOG)) CHAT = TRUE;

   
   if(CHAT)
   {
      ASPrintf(NULL,logstring,"-> %s",ID_STRING);
      Log(logstring);
   }

   AFPrintf(NULL,sout,"%s\n",ID_STRING);

/// CheckDLGMAILSTOP
   if(Exists("Env:DLGMailStop"))
   {
      if(DEBUG || CHAT) AFPrintf(NULL,sout,"DLGMail told me to stop hunting DLGHub files");
      if(DLGBase) CloseLibrary(DLGBase);
      exit(0);
   }
//-

   Index = LoadConfig();

   if(Index == -1)
   {
      Log(" ! Error loading config!");
      Log("<- DLGHub terminating\n");
      exit(20);
   }

   if(Index > 0)
   {
      GetClk();
      HubScan();
      if(CFG)  FreeCFG();
   }

   if(CHAT) Log("<- End DLGHub\n");
   if(DLGBase) CloseLibrary(DLGBase);
   exit(0);
}
//-

/// GetClk
void GetClk(void)
{
   UBYTE clock[10];

   char *days[]={"Sun","Mon","Tue","Wed","Thu","Fri","Sat"};
   char *months[]={"","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"};

   getclk(clock);

   DAY=clock[0];
   YEAR=clock[1]+80;
   MONTH=clock[2];
   DATE=clock[3];
   HOUR=clock[4];
   MIN=clock[5];

   ASPrintf(NULL,DATESTR,"%s %2d %s %2d",days[DAY],DATE,months[MONTH],YEAR);
   ASPrintf(NULL,TIMESTR,"%02d:%02d",HOUR,MIN);
   ASPrintf(NULL,DATETIMESTR,"%s %s",DATESTR,TIMESTR);
}
//-

/// 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. Reboot your system!\n");
         return(0);
      }

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

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


