
#include <exec/types.h>
#include <exec/memory.h>
#include <dos/dos.h>
#include <clib/exec_protos.h>
#include <clib/dos_protos.h>
#include <clib/alib_protos.h>

#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <ctype.h>
#include <time.h>


#ifdef __SASC
int CXBRK(void) { return(0); }
int _CXBRK(void) { return(0); }
void chkabort(void) {}
#endif

#include <HBBS/ANSI_Codes.h>
#include <HBBS/Defines.h>
#include <HBBS/types.h>
#include <HBBS/structures.h>
#include <HBBS/hbbscommon_protos.h>
#include <HBBS/hbbscommon_pragmas.h>
#include <HBBS/Hbbsnode_protos.h>
#include <HBBS/Hbbsnode_pragmas.h>
#include <HBBS/release.h>
char *versionstr="$VER: AddCreds "RELEASE_STR;

struct Library *HBBSCommonBase=NULL;
struct Library *HBBSNodeBase=NULL;

struct BBSGlobalData *BBSGlobal=NULL;
struct NodeData *N_ND=NULL;
int N_NodeNum=-1;
char outstr[1024]; // temp string for displaying text..

static VOID cleanup(ULONG num)
{
  if (HBBSNodeBase)
  {
    HBBS_CleanUpDoor();
    CloseLibrary (HBBSNodeBase);
  }

  if (HBBSCommonBase)
  {
    HBBS_CleanUpCommon();
    CloseLibrary (HBBSCommonBase);
  }

  if (num) printf("Door Error = %d\n",num);

  exit(0);
}

static VOID init(char *name)
{
  if(!(HBBSCommonBase = OpenLibrary("HBBSCommon.library",0)))
  {
    cleanup(1);
  }

  if (!(HBBS_InitCommon()))
  {
    cleanup(2);
  }

  if(!(HBBSNodeBase = OpenLibrary("HBBSNode.library",0)))
  {
    cleanup(3);
  }

  if (!(HBBS_InitDoor(N_NodeNum,name)))
  {
    cleanup(4);
  }
  SetProgramName(name);
}

void AwardCredits(V_BIGNUM ConfNum,LONG Creds,char *FileName)
{

  // *C* update for conference accounting..

  N_ND->User.CallData.UploadBytes+=Creds;
  N_ND->User.NormalData.UploadBytes+=Creds;
  N_ND->User.CallData.UploadFiles++;
  N_ND->User.NormalData.UploadFiles++;

//*** Protocol door now handles these now...
//
//  N_ND->User.CallData.ActualUploadBytes+=Creds;
//  N_ND->User.NormalData.ActualUploadBytes+=Creds;
//  N_ND->User.CallData.ActualUploadFiles++;
//  N_ND->User.NormalData.ActualUploadFiles++;

}

void DoorMain(int argc,char *argv[])
{
  struct CfgFileData *AutoAwardCFG=NULL;
  struct List *AwardFile=NULL;
  struct List *AwardOpts=NULL;
  LONG AwardSize=0,p,Matched=0;
  V_BOOL StopOnFirstMatch=TRUE;
  BOOL ExaminedOK=FALSE,FoundMatch,Done=FALSE;
  ULONG AwardFiles=0;
  V_BIGNUM ConfNum;
  struct Node *node,*node2;
  char matchstr[256];
  BPTR FL;
  struct FileInfoBlock FB;

  ConfNum=atoi(argv[2]);

  if ((ConfNum<1) || (ConfNum>BBSGlobal->Conferences))
  {
    DOOR_WriteText("Invalid Conference!\r\n");
  }
  else
  {
    // get details about the file that was uploaded..

    strcpy(outstr,N_ND->NodeSettings.NodePlayPen);
    strcat(outstr,argv[3]);
    if (FL=Lock(outstr,ACCESS_READ))
    {
      if (Examine(FL,&FB))
      {
        ExaminedOK=TRUE;
      }
      UnLock(FL);
    }
    if (!ExaminedOK)
    {
      sprintf(outstr,"Error Awarding Credits\n"
                     "User: %s\n"
                     "File: %s\n"
                     "Reason: Could Not find File!",N_ND->User.CallData.Handle,argv[3]);
      HBBS_LogError(BBSGlobal->ErrorLogFile,ERR_GENERAL,outstr,TYPE_WARNING);
      DOOR_WriteText("Could Not Find File!\r\n");
    }
    else
    {
      // get the filename of the config file (same dir as executable..)
      strcpy(outstr,argv[0]);
      if ((p=iposition(".HBBS",outstr))==(strlen(outstr)-5))
      {
        outstr[p]=0; //terminate string
      }
      strcat(outstr,".CFG");


      if (AutoAwardCFG=HBBS_LoadConfig(outstr,LCFG_NONE))
      {
        HBBS_GetSetting(AutoAwardCFG,(void *)&StopOnFirstMatch,VTYPE_BOOL,"StopOnFirstMatch",OPT_SINGLE);
        if (AwardFiles=HBBS_GetSetting(AutoAwardCFG,(void *)&AwardFile,VTYPE_STRINGLIST,"AwardFile",OPT_MULTI))
        {
          if (AwardFiles==HBBS_GetSetting(AutoAwardCFG,(void *)&AwardOpts,VTYPE_STRINGLIST,"AwardOpts",OPT_MULTI))
          {
            for (node = AwardFile->lh_Head , node2 = AwardOpts->lh_Head ; node->ln_Succ && node2->ln_Succ && !Done ; node =node->ln_Succ,node2 =node2->ln_Succ)
            {
              FoundMatch=FALSE;
              ParsePatternNoCase(node->ln_Name,matchstr,255);
              if (MatchPatternNoCase(matchstr,argv[3]))
              {
                if (node2->ln_Name[0]) // a blank string ?
                {
                  sscanf(&node2->ln_Name[1],"%ld",&AwardSize);
                  if (AwardSize>0)
                  {
                    switch(node2->ln_Name[0])
                    {
                      case '+':
                        FoundMatch=TRUE;
                        AwardSize=FB.fib_Size+AwardSize;
                        break;
                      case '-':
                        FoundMatch=TRUE;
                        AwardSize=FB.fib_Size-AwardSize;
                        break;
                      case '*':
                        FoundMatch=TRUE;
                        AwardSize=FB.fib_Size*AwardSize;
                        break;
                      case '/':
                        FoundMatch=TRUE;
                        AwardSize=FB.fib_Size/AwardSize;
                        break;
                    }
                    if (FoundMatch)
                    {
                      Matched++;
                      sprintf(outstr,ANSI_RESET ANSI_FG_YELLOW "Awarding %ld%s=%ld credits for %s\r\n" ANSI_RESET,FB.fib_Size,node2->ln_Name,AwardSize,argv[3]);
                      DOOR_WriteText(outstr);
                      AwardCredits(ConfNum,AwardSize,argv[3]);
                    }
                  }
                }
              }
              if (StopOnFirstMatch && FoundMatch) Done=TRUE;
            }
            if (Matched==0)
            {
              sprintf(outstr,ANSI_RESET ANSI_FG_GREEN "Awarding %ld credits for %s\r\n" ANSI_RESET,FB.fib_Size,argv[3]);
              DOOR_WriteText(outstr);
              AwardCredits(ConfNum,FB.fib_Size,argv[3]);
            }
          }
          else DOOR_WriteText("Config File Mismatch\r\n");
        }
      }
      else
      {
        AwardCredits(ConfNum,FB.fib_Size,argv[2]);
      }
    }
  }
}

int main(int argc,char *argv[])
{
  if (sscanf(argv[1],"%d",&N_NodeNum)==0)
  {
    printf("Invalid/No Paramaters for door!\n");
    exit (20);
  }
  init("AddCreds");

  if (BBSGlobal=HBBS_GimmeBBS())
  {
    if (N_ND=HBBS_NodeDataPtr(N_NodeNum)) // this should not fail in normal circumstances..
    {
      DoorMain(argc,argv);
    }
  }
  cleanup(0);
}
