/*************************************************************************
** $VER: CDRun.c 1.1 (4.8.95)
** Copyright © 1995 Oliver Roberts
**
** Compiled with Dice 3.01
**
** Description: Simple CLI command which takes a path to a command as a
**              parameter, CDs to the location of that command and
**              attempts to execute it.
**
** Example: "CDRun SYS:Utilities/Format" does the same as this:
**
**          "CD SYS:Utilities"
**          "Format"
*/

#include <exec/types.h>
#include <exec/execbase.h>
#include <dos/dos.h>

#include <proto/dos.h>
#include <proto/exec.h>

#include <stdlib.h>

const char verstag[] = "\0$VER: CDRun 1.1 (" __COMMODORE_DATE__ ")";
const char copyright[] = "Copyright © 1995 Oliver Roberts";

LONG Args[1];

void PrintError(void)
{
   UBYTE buffer[80];
   if (Fault(IoErr(),NULL,buffer,80)) {
      PutStr(buffer);
      PutStr("\n");
   }
}

void _main(void)
{
   struct RDArgs *rdargs;
   char *path;
   char *ptr;
   char store;
   int ret = RETURN_OK;
   BPTR olddir = -1;
   BPTR dirlock;

   if (SysBase->LibNode.lib_Version < 36) _exit(RETURN_FAIL);

   rdargs = ReadArgs("COMMAND/F",Args,NULL);

   if (Args[0]) {
      path = (char *)Args[0];
      ptr = PathPart(path);
      store = *ptr;
      *ptr = '\0';
      if (dirlock = Lock(path,ACCESS_READ)) {
         olddir = CurrentDir(dirlock);
      }
      else {
         PrintError();
      }
      *ptr = store;

      ret = SystemTagList(FilePart(path),NULL);

      if (olddir != -1) CurrentDir(olddir);
      UnLock(dirlock);
   }

   FreeArgs(rdargs);

   _exit(ret);
}
