/* ----------------------------------------------------------------
 *
 *  Project: Filevirus Library
 *
 *  Program: fvfind.c
 *
 *  Author : Bjorn Reese <breese@imada.ou.dk>
 *
 *  Short  : Example of a simple virus detector that uses unpack.library
 *           Compile with "sc LINK fvfind.c"
 *
 * ---------------------------------------------------------------- */

#include <stdio.h>

#include <exec/types.h>
#include <exec/memory.h>
#include <dos/dos.h>
#include <dos/doshunks.h>
#include <dos/dostags.h>
#include <proto/exec.h>
#include <proto/dos.h>

#include <libraries/unpack.h>
#include <proto/unpack.h>
#include <libraries/filevirus.h>
#include <proto/filevirus.h>

extern struct Library *SysBase;
struct FilevirusBase *FilevirusBase=NULL;

/* ---------------------------------------------------------------- */

__saveds __asm void Scanner(
  register __a1 struct FilevirusNode *p,
  register __a4 struct UnpackInfo *pu)
{

  p->fv_Buffer    = pu->ui_DecrunchAdr;
  p->fv_BufferLen = pu->ui_DecrunchLen;

  printf("File: '%s' ", (pu->ui_UseFilenamePointer ? pu->ui_LoadNamePoi : pu->ui_Filename));

  if ( !fvCheckFile(p, 0) ) {

    if (p->fv_FileInfection != NULL) {

      printf("*** virus '%s' found\n", (p->fv_FileInfection)->fi_VirusName);

    } else printf("clean\n");

  } else printf("error %d\n", p->fv_Status);
}

/* ---------------------------------------------------------------- */

void UnpackScanner(struct FilevirusNode *p, char *fname)
{
  struct Library *UnpackBase=NULL;
  struct UnpackInfo *pu;

  if ( UnpackBase = OpenLibrary("unpack.library", 39) ) {

    if ( pu = upAllocCInfo() ) {

      pu->ui_Filename = fname;
      pu->ui_Path     = "TEMP:klejne/"; /* must be unique as all files here will be deleted */
      pu->ui_Jump     = (void (*)(void *, void *))Scanner;
      pu->ui_TrackJump= (void (*)(void *, void *))Scanner;
      pu->ui_UserData = p;
      pu->ui_Flag     = 1<<UFB_Delete;

      if ( upDetermineFile(pu, fname) ) {

        printf("Cruncher: %s\n", pu->ui_CruncherName);
        upUnpack(pu);

      } else {

        if ( upLoadFile(pu) ) {
          Scanner(p, pu);
          upFreeFile(pu);
        }
      }
      upFreeCInfo(pu);
    }
    CloseLibrary(UnpackBase);
  }
}
/* ---------------------------------------------------------------- */

int main(int argc, char *argv[])
{
  struct FilevirusNode *p;

  if ( FilevirusBase = (struct FilevirusBase *)OpenLibrary("filevirus.library", 2) ) {

    if ( p = fvAllocNode() ) {

      UnpackScanner(p, argv[1]);
      fvFreeNode(p);

    } else fprintf(stderr, "fvAllocNode() failed\n");

    CloseLibrary((struct Library *)FilevirusBase);

  } else fprintf(stderr, "Cannot open 'filevirus.library'\n");

}
