/************************************************************************

        BATCH  (c) 1988 Tom Beale
        Execute Dos Commands and Batch Files from WorkBench                

************************************************************************/
#include <stdio.h>
#include <dos.h>
#include <string.h>
#include <error.h>
#include <ctype.h>
#include <exec/types.h>

#include <graphics/gfxmacros.h>
#include <intuition/intuition.h>
#include <workbench/startup.h>
#include <workbench/workbench.h>
#include <workbench/icon.h>
#include <libraries/dosextens.h>

extern struct WBStartup *WBenchMsg;
struct IntuiMessage *message;

struct WBStartup *WBS;
struct WBArg *arg;
struct DiskObject *DO;
struct IntuitionBase *IntuitionBase;
struct IconBase *IconBase;

char *name, *fname, uargs[100], buff[100], **tool, hold, *cmd, *args;
char tname[100], b[100], *a, *c, utemp[100];

extern int errno;                /* Declare external variables so if     */
extern int sys_nerr;             /* there are problems opening the file  */
extern char *sys_errlist[];      /* so we can find out why.              */

void main(argc,argv)
   int argc;
   char *argv[];
   {
   int ret;
   char *a;
   LONG node;

   if (argc) PrintOut();

   if ((IntuitionBase =
      (struct IntuitionBase *)OpenLibrary("intuition.library",1)) == NULL)
         printf("Intuition Library not Open");

   node  = (struct DosLibrary *) OpenLibrary( "dos.library" );
   IconBase = OpenLibrary("icon.library",0);
       if (IconBase == NULL) xxerr("Can't Open Icon Library");

   cmd = "EXECUTE RAM:BatchTemp";
   ret = WBArgFN(WBenchMsg);                  /* Get Name of Batch File */
   if (name == NULL) xxerr(" > WBArg ????");  /* Did We Get IT?         */  
   MakeTemp();                                /* Copy File to RAM:      */
   if (uargs) a = strcat(cmd,uargs);
   ret = Execute(cmd,0,0);                    /* Execute it             */
   ret = remove("RAM:BatchTemp");             /* Delete RAM: File       */
   FreeDiskObject(DO);
   if(hold) ret = getchar();
   }


/*
   ------------------------------------------------------ WBArg FileName
*/

WBArgFN(msg)
   struct WBStartup *msg;
      {
      struct WBArg *arg;          /*  Local Variables             */
      int args, ret, i, echo;
      char cbuff[100];   

      hold = 1;
      echo = 1;
      c = *cbuff;

      arg = msg->sm_ArgList;        /* Extract WBArguments          */
      args = msg->sm_NumArgs;       /* How Many were there?         */

      arg++;                        /* Incriment arg (who knows?)   */

      CurrentDir(arg->wa_Lock);     /* Set CD to where Icon resides */

      name = arg->wa_Name;           /* Get Name of File             */
      if (name==NULL) return(1);     /*     Check for errors         */
      
      ret = strcpy(tname,name);
      fname = strdup(name);  
      DO = GetDiskObject(tname);     /* Get Icon Structure           */
      tool = DO->do_ToolTypes;       /* Extract ToolTypes Array      */

      for(ret=0;tool[ret]!=NULL;ret++) /* Get Paramaters from Icon   */
         {
         if (stricmp(tool[ret],"NOHOLD")   == 0) hold = 0;
         if (stricmp(tool[ret],"CLEAR")    == 0) putchar(12);
         if (stricmp(tool[ret],"EXIT")     == 0) exit(0);
         if (stricmp(tool[ret],"ECHO ON")  == 0) echo = 1;
         if (stricmp(tool[ret],"ECHO OFF") == 0) echo = 0;

	 switch(tool[ret][0])
            {
            case '>':                    /* Get Arg for Batch File    */
               tool[ret][0]=' ';
               a = strcat(cmd,tool[ret]);
               break;

            case '?':                    /* Print Line to Screen      */              
               tool[ret][0]=' ';
               printf("%s\n",tool[ret]);
               break;

            case '-':                    /* Execute Command (no args) */ 
               tool[ret][0]=' ';
               if (echo) printf("%s\n",tool[ret]);
               i=Execute(tool[ret],0,0);
               break;

            case '*':                    /* Execute Command (args)    */ 
               tool[ret][0]=' ';
               strcpy(utemp,tool[ret]);
               c = strcat(utemp,uargs);
               if (echo) printf("%s\n",utemp);
               i = Execute(utemp,0,0);
               strset(uargs,'\0');
               strset(utemp,'\0');
               break;

            case ':':                    /* Query User for Input       */
               tool[ret][0]=' ';
               printf("%s ",tool[ret]);
               c = gets(b);
               strins(b," ");
               strcat(uargs,b);
               break;
            }
         }
      return(0);
      }
/*
   ----------------------------------------------- Copy Batch File to RAM:
                                  (Simpler than constructing the pathname)
*/

MakeTemp()
      {                                  /* Declare local variables   */
      FILE *sfp, *dfp;                     
      long c, ret;

      sfp = fopen(fname,"r");            /* Open Source (text) file     */
      if (sfp == NULL)                   /* Handle Errors               */
         {
         xxerr("Can't Open Batch File: %s\n ",sys_errlist[errno]);
         }

      dfp = fopen("RAM:BatchTemp","w");  /* Open Dest (temp) file      */
      if (dfp == NULL)
         {
         xxerr("Can't Create RAM: Temp File: %s\n ",sys_errlist[errno]);
         }

      /*
             ------------------------------  Replace Text file with Temp file
      */

      do {                           /* Begin Copy Loop                 */
         c = fgetc(sfp);             /* Get char from Temp file         */
         if (c == EOF) break;        /* Test for End of File            */
         c = fputc(c,dfp);           /* Put Char into Text File         */
         } while (c != EOF);

      ret = fclose(sfp);
      if (ret == -1) printf("\nSource File did not close properly(2).\n");
      ret = fclose(dfp);
      if (ret == -1) printf("\nDestination File did not close properly(2).\n");

      return(0);
      }
/*
  --------------------------------------------------- Graceful Exit
*/
xxerr(msg)
   char *msg;
   {
   int ret;
   if (IntuitionBase) CloseLibrary(IntuitionBase);
   if (msg)
       { 
       printf("    -%s\n",msg);
       ret = getchar();
       }
   exit(0);
   }
/*
 --------------------------------------------------- Print Help Screen
*/
PrintOut()
   {
   printf("\n");
   printf("BATCH  -  Execute Batch file from WorkBench\n");
   printf("          %c 1988 Tom Beale\n",169);
   printf("\n");
   printf("  Tool Types command characters (Must be first\n");
   printf("  character in string):\n");
   printf("     ?<string>    Print string.\n");
   printf("     ><arguments> Pass argument to batch file.\n");
   printf("     :<prompt>    Prompt user for argument.\n");
   printf("     -<command>   Run CLI Command.\n");
   printf("     *<command>   Run CLI Command using input from user.\n");
   printf("\n");
   printf("  Additional commands:\n");
   printf("     nohold   - Close window after batch file executes\n");
   printf("     exit     - Terminate execution (don't run batch file)\n");
   printf("     clear    - Clear Output Window\n");
   printf("     echo on  - Echo icon commands (default)\n");
   printf("     echo off - Do not echo icon commands\n");
   printf("\n");
   exit(0);
   }