/****************************************************************************
 *	EnvTool 0.1
 *
 *	Alpha Release, 27 December 1993
 *	Compiled with DICE
 *
 *	Placed in the public domain, by Dan Fish
 *	No rights reserved.
 *
 *	Please freely-distribute this program! Enhance it, send it back to 
 *	us for use with the AmigaLib library.  (After all... it's to make
 *	the library better for you!)
 *
 *	Amiga Library Services
 *	610 N. Alma School Rd.
 *	Suite 18
 *	Chandler, Az.  85224-3687
 *
 *   or Email to:
 *
 *      fnf@fishpond.cygnus.com
 *
 *
 ****************************************************************************/
#include <exec/types.h>
#include <libraries/dos.h>
#include <workbench/workbench.h>
#include <workbench/startup.h>

#include <clib/exec_protos.h>
#include <clib/dos_protos.h>
#include <clib/intuition_protos.h>
#include <clib/icon_protos.h>

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <stdarg.h>

/* 
 *  Function prototypes
 */

void  cleanexit( LONG );
void  HandleArg( char * );
long  Req( UBYTE *, UBYTE *, ... );
char *TTString( struct DiskObject *, char *, char * );

#define  EXEVERSION          "v0.1"
#define  EXENAME             "EnvTool"

/*
 * DCBack required data. DCBack is a tiny link library
 * written by Jan van den Baard to make it possible to write
 * auto-detachable programs with DICE. 
 */

UBYTE                       *_procname      = EXENAME "_" EXEVERSION;
UBYTE                       *_template      = NULL;
UBYTE                       *_exthelp       = NULL;
LONG                         _stack         = 2048L;
LONG                         _priority      = NULL;
LONG                         _BackGroundIO  = NULL;

/*
 * The following libraries are all auto-init.
 */
extern struct IntuitionBase        *IntuitionBase;
extern struct UtilityBase          *UtilityBase;
extern struct GadToolsBase         *GadToolsBase;

/*
 * Required libraries that are not in DICE's
 * auto-init library.
 */

struct Library              *IconBase      = NULL;
struct Library              *WorkbenchBase = NULL;

/* The Default command to run if none specified via ToolTypes */

UBYTE   *DEFAULT_CMD =   "Run SYS:Utilities/More ";

/* Used for debugging	*/
UBYTE *conwinname   = "CON:10/10/620/180/libreader.new";


/*
 * Shell version string.
 */
static UBYTE EnvToolVer[]        =       "$VER: EnvTool 0.1 (27-Dec-93)";

/* Opens and allocations we must clean up */

FILE *conwin = NULL;  /* simple debugging	*/
LONG olddir = -1;
struct WBStartup *WBenchMsg = NULL;

int main( int argc, char **argv )
{
  fprintf(stderr, "%s %s must be started from the WorkBench\n"
		EXENAME, EXEVERSION);
  exit(-1);
}

void wbmain( struct WBStartup *wbs )
 {
    struct WBArg *wbarg;
    SHORT i;
    int error;
    WBenchMsg = wbs;

    if ( ! ( IconBase = OpenLibrary( "icon.library", 34L ))) {
        error = 21L;
    	cleanexit( error );
    }

    if ( ! ( WorkbenchBase = OpenLibrary( "workbench.library", 37L ))) {
        error = 22L;
    	cleanexit( error );
    }

    if (WBenchMsg ) {
       /*
        * When WBenchMsg is non-null it means that
        * Libreader was started from the workbench.
        */

       /* Used for some simple debugging...
       if(!(conwin = fopen(conwinname,"r+")))
             cleanexit(30L);*/

 
      /* Note wbarg++ at end of FOR statement steps through wbargs.
       * First arg is our executable (tool).  Any additional args
       * are projects/icons passed to us via either extend select
       * or default tool method.
       */

       for(i=0, wbarg=WBenchMsg->sm_ArgList; i < WBenchMsg->sm_NumArgs;
              i++, wbarg++)
        {


          /* if there's a directory lock for this wbarg, CD there */
          olddir = -1;

          if((wbarg->wa_Lock)&&(*wbarg->wa_Name))
              olddir = CurrentDir(wbarg->wa_Lock);

          if((i>0)&&(*wbarg->wa_Name))
           {
	    HandleArg(wbarg->wa_Name);		
	   }

          if(olddir != -1)  CurrentDir(olddir); /* CD back where we were */

         } /* end of for */

       } /* end of if */

    cleanexit(0L);

  } /* end of main */

void HandleArg(char *arg)
 {
  struct DiskObject *diskobj;
  char *env = (char *)NULL;
  char *env_ttype = (char *)NULL;
  char *def_ttype = (char *)NULL;
  char *prefix;

  char temp[81];
  char cmdbuff[81]; 
  int ierr;

  /* Open up the icon for this project */

  if(!(diskobj = GetDiskObject(arg)))
   {
    (void)Req("Uh-Oh!","Cannot access icon for file:\n\"%s\"", arg); 
    return;
   }

  /* start with the basic built-in "default" command */
  sprintf(temp,"%s %s",DEFAULT_CMD,arg);

  /* if a default tool is specified, update the command buffer */
  def_ttype = TTString(diskobj,"DEFAULT",NULL);
  if(def_ttype)
      sprintf(temp,"%s %s",def_ttype,arg);

  /* if an environment variable is specified and set, update the command */
  env_ttype = TTString(diskobj,"ENV", NULL);
  if (env_ttype)
   {
    if(env = getenv(env_ttype))
      sprintf(temp,"%s %s",env,arg);
   }

  /* Check for a PREFIX tooltype */

  prefix = TTString(diskobj,"PREFIX", NULL);
  if(prefix)
      sprintf(cmdbuff,"%s %s",prefix,temp);
  else
      strcpy(cmdbuff,temp);

  /* spawn the command */
  ierr = system(cmdbuff);

  if (ierr != 0)
     (void)Req("Oops!","The command:\n\"%s\"\n\nReturned Code = %ld\n",
		 cmdbuff,ierr); 
 
   (void)FreeDiskObject(diskobj);

}

void cleanexit( LONG code )
{
    if (conwin)             fclose(conwin);
    if ( WorkbenchBase )    CloseLibrary( WorkbenchBase );
    if ( IconBase )         CloseLibrary( IconBase );
    exit( code );

}

/*
 * Put up a simple requester.
 */
long Req( UBYTE *gadgets, UBYTE *body, ... )
{
    static struct EasyStruct req = {
        sizeof( struct EasyStruct ), NULL, NULL, NULL, NULL };
    va_list                  args;
    LONG                     rc;

    va_start( args, body );

    req.es_Title        = EXENAME;
    req.es_TextFormat   = body;
    req.es_GadgetFormat = gadgets;

    rc = EasyRequestArgs( NULL, &req, NULL, args );

    va_end( args );

    return( rc );
}

/* 
 * TTString returns the argument of the specified String type ToolType 
 * (Provided it exists of course!) ... Kinda like ArgString()
 */

char *TTString(struct DiskObject *diskobj, char *tt, char *def)
{
  char *string;
  if (diskobj)
    if (string = FindToolType(diskobj->do_ToolTypes, tt))
      return(string);
  return(def);
}
