/*
 * Kludge for handling systems that can't cope with multiple
 * external definitions of a variable.  In ONE routine (tar.c),
 * we #define TAR_EXTERN to null; here, we set it to "extern" if
 * it is not already set.
 */

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <fcntl.h>
#include <dos/rdargs.h>
#include <dos.h>
#include <exec/types.h>
#include <clib/dos_protos.h>
#include <clib/exec_protos.h>
#include <clib/locale_protos.h>
#include <libraries/locale.h>
#include <proto/dos.h>
#include <pragmas/exec_pragmas.h>
#include <pragmas/dos_pragmas.h>
#include <exec/execbase.h>
#include "obj.h"

#define USAGE		"usage: %s [TYPE classname] [NOIO] file...\n"

extern char *ckfmsg;
extern struct magic magic[];
char execbuffer[256];
int 	debug = 0, 	/* huh? */
	nbytes = 0,	/* number of bytes read from a datafile */
	nmagic = 0;	/* number of valid magic[]s */
FILE *efopen();
char magicfile[80] = "ENV:OBJ/";	/* where magics be found */
char *progname;
char *version = "$VER: Obj 1.3 (Nov. 1992)";
struct stat statbuf;
void process(char *inname);
int  f_req(char *buf);
long obj_type;
BPTR obj_win;

long argarr[] = { 0L, 0L, 0L, 0L };
char *templ = "TYPE=-t/K,FILES/M,NOIO/S";

#define ARG_TYPE  0
#define ARG_FILES 1
#define ARG_NOIO  2

/*
 * main - parse arguments and handle options
 */

void main(int argc, char *argv[])
 {
	int ret = 0;
//	struct Catalog *catalog;
	struct RDArgs *rda;         /* structure vor ReadArgs */
   char **files, tmpfile[40], *s;
   BPTR l;
   struct FileInfoBlock fib;
   time_t t;
	char   path_buf[PATHSIZE];

	progname = argv[0];
 
//   LocaleBase = OpenLibrary((UBYTE *)"locale.library", 37L);
//   if (LocaleBase == NULL)
//     {
//       fprintf(stderr, "%s: fatal: WB >2.1 required\n", progname);
//       exit(10);
//     }
//   catalog = OpenCatalog(NULL, (STRPTR) "obj", TAG_DONE);

   sprintf(tmpfile, "T:obj_tmp_%ld", time(&t));
   rda = ReadArgs((UBYTE *)templ, argarr, NULL);
   if (!rda)
     {
		 fprintf(stderr, USAGE, progname);
       exit(1);
     }

   if (argarr[ARG_TYPE])
   	strcat(magicfile, (char *)argarr[ARG_TYPE]);
   else
      strcat(magicfile, "VIEW");

   if (argarr[ARG_NOIO])
      strcpy(tmpfile, "NIL:");

   obj_win = Open(tmpfile, MODE_NEWFILE);
   if (!obj_win)
     {
       fprintf(stderr, "%s: Could not open output window.\n", progname);
       exit(5);
     }
	ret = apprentice(magicfile);
   if (argarr[ARG_FILES])
     {
       files = (char **) argarr[ARG_FILES];
       while (*files)
         {
	        process(*files);
	        files++;
	      }
	  }
	else  /* no parameter given */
	  {
		 if (f_req(path_buf) == 1)
		   {
		     process(path_buf);
		   }
     }

   FreeArgs(rda);
//	CloseLibrary(LocaleBase);
   Close(obj_win);
   /* now test, if we need to open a window */
   if (argarr[ARG_NOIO])
       exit(0);
   l = Lock(tmpfile, ACCESS_READ);
   Examine(l, &fib);
   UnLock(l);
   if (fib.fib_Size > 0)   /* yes, there was output */
     {
       s = getenv("PAGER");
       if (s)
	       strcpy(execbuffer, s);
	    else
   	    strcpy(execbuffer, "Run More");
       strcat(execbuffer, " ");
       strcat(execbuffer, tmpfile);
       system(execbuffer);
	  }
   DeleteFile(tmpfile);
	exit(0);
 }

/*
 * unwrap -- read a file of filenames, do each one.

void unwrap(char *fn)
 {

#define FILENAMELEN 128

	char buf[FILENAMELEN];
	FILE *f;

	if ((f = fopen(fn, "r")) == NULL)
		(void) fprintf(stderr, "%s: file %s unreadable\n",
			progname, fn);
	else {
		while (fgets(buf, FILENAMELEN, f) != NULL) {
			buf[strlen(buf)-1] = '\0';
			process(buf);
		}
		(void) fclose(f);
	}
 }
 */

/*
 * process - process input file
 */

void process(char *inname)
 {
	int	fd, i;
	char	buf[HOWMANY], sys_buf[256], *s;

	/*
	 * first try judging the file based on its filesystem status
	 * Side effect: fsmagic updates global data `statbuf'.
	 */

   strcpy(execbuffer, "echo no entry for: ");  /* default */

	if (fsmagic(inname) != 0) /* file stat() magic */
     {
		 /*NULLBODY*/;
	  } 
   else if ((fd = open(inname, 0)) < 0) 
     {
		 /* We can't open it, but we were able to stat it. */
		 if (statbuf.st_mode & 0002) 
           ckfputs("writeable, ", stdout);
		 if (statbuf.st_mode & 0111) 
           ckfputs("executable, ", stdout);
		 warning("can't read", "");
	  } 
    else 
     {
readit:
		/*
		 * try looking at the first HOWMANY bytes
		 */
		if ((nbytes = read(fd, buf, HOWMANY)) == -1)
			warning("read failed", "");
		if (nbytes == 0) 
       {
//			ckfputs("empty", stdout);
			obj_type = EMPTY;
	    } 
    else
		/*
		 * try tests in /etc/magic (or surrogate magic file)
		 */
		if (softmagic(buf) == 1)
			/*NULLBODY*/;
		else if (ascmagic(buf) == 1)
			/*
			 * try known keywords, check for ascii-ness too.
			 */
			/*NULLBODY*/;
		else 
       {
			/*
			 * abandon hope, all ye who remain here
			 */
//			ckfputs("data", stdout);
         obj_type = ELSE;
 		 }
	}

   if (obj_type)
     {
       for (i = 0; i < nmagic && obj_type; i++)
         {
           if (obj_type == magic[i].type)
             {
               strcpy(execbuffer, magic[i].desc);
               obj_type = 0;       /* terminate loop */
             }
         }
     }
	s = strstr(execbuffer, "[]");
   if (s)
     {
       memcpy(s, "%s", 2);
       sprintf(sys_buf, execbuffer, inname);
     }
   else
       sprintf(sys_buf, "%s %s", execbuffer, inname);
//	if (debug)
//      fprintf(stderr, "%s: executing %s\n", progname);
   Execute(sys_buf, NULL, obj_win);
 }
