/*
 *  This file is part of ixemul.library for the Amiga.
 *  Copyright (C) 1991, 1992  Markus M. Wild
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Library General Public
 *  License as published by the Free Software Foundation; either
 *  version 2 of the License, or (at your option) any later version.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Library General Public License for more details.
 *
 *  You should have received a copy of the GNU Library General Public
 *  License along with this library; if not, write to the Free
 *  Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *
 *  22-jan-92	-mw-	restore sigmask before calling system()
 */

#define KERNEL
#include "ixemul.h"
#include <ctype.h>
#include <sys/wait.h>

#ifdef DEBUG
#define DP(a) kprintf a
#else
#define DP(a)
#endif

#define NO_PROTOTYPES
#include <libraries/arpbase.h>  /* HAS! to be V39 or higher! */
#undef NO_PROTOTYPES

#define BASE_EXT_DECL
#define BASE_PAR_DECL	
#define BASE_PAR_DECL0	
#define BASE_NAME	ix.ix_arp_base
#include <inline/arp.h>

/* 2.0 support */
#include "gcc:include20/utility/tagitem.h"
#include "gcc:include20/dos/dostags.h"
#define BASE_EXT_DECL
#define BASE_PAR_DECL	
#define BASE_PAR_DECL0	
#define BASE_NAME	ix.ix_dos_base
__inline static LONG RunCommand(BASE_PAR_DECL BPTR seg, long int stack, UBYTE* paramptr, long int paramlen)
{
	BASE_EXT_DECL
	register LONG res __asm("d0");
	register void *a6 __asm ("a6");
	register BPTR d1 __asm("d1");
	register long int d2 __asm("d2");
	register UBYTE* d3 __asm("d3");
	register long int d4 __asm("d4");

	a6 = BASE_NAME;
	d1 = seg;
	d2 = stack;
	d3 = paramptr;
	d4 = paramlen;
	__asm volatile ("
	jsr a6@(-0x1f8)"
	: "=r" (res)
	: "r" (a6), "r" (d1), "r" (d2), "r" (d3), "r" (d4)
	: "d0", "d1", "a0", "a1", "d2", "d3", "d4");
	return res;
}
#ifndef CMD_SYSTEM
#define CMD_SYSTEM	-1
#define CMD_INTERNAL	-2

struct Segment {
	BPTR seg_Next;
	LONG seg_UC;
	BPTR seg_Seg;
	UBYTE seg_Name[4];	/* actually the first 4 chars of BSTR name */
};
#endif
__inline static struct Segment* FindSegment(BASE_PAR_DECL UBYTE* name, struct Segment* seg, long int system)
{
	BASE_EXT_DECL
	register struct Segment* res __asm("d0");
	register void *a6 __asm ("a6");
	register UBYTE* d1 __asm("d1");
	register struct Segment* d2 __asm("d2");
	register long int d3 __asm("d3");

	a6 = BASE_NAME;
	d1 = name;
	d2 = seg;
	d3 = system;
	__asm volatile ("
	jsr a6@(-0x30c)"
	: "=r" (res)
	: "r" (a6), "r" (d1), "r" (d2), "r" (d3)
	: "d0", "d1", "a0", "a1", "d2", "d3");
	return res;
}

extern int _dos20; /* set in crt0.c */

#if __GNUC__ != 2
#define alloca __builtin_alloca
#endif

extern BPTR __load_seg (char *name, char **args, BPTR *interp_lock);

int
ssystem(char *argline)
{
  int rc, err = 0;
  UBYTE *arg, *index();
  UBYTE *tmp;
  int stack_size;
  struct CommandLineInterface *CLI;
  struct Process *me;
  int omask;

  omask = syscall (SYS_sigsetmask, ~0);
  me = (struct Process *)FindTask(0);
  CLI = BTOCPTR (me->pr_CLI);
  stack_size = CLI ? CLI->cli_DefaultStack * 4 : me->pr_StackSize;
  if (stack_size <= 4096) stack_size = 250000;
 
  /* the +1 is to get a cheap way to transform this into a BSTR */
  tmp = alloca (strlen (argline) + 6);
  tmp = LONG_ALIGN (tmp);
  tmp++;

  strcpy (tmp, argline);

  while (*tmp == ' ' || *tmp == '\t') ++tmp;
  /* not needed with custom load-seg function */
  if (! _dos20)
    while (tmp[0] == '.' && tmp[1] == '/') tmp += 2;

  if (arg = index(tmp, ' '))  *arg++ = 0;

  if (! _dos20)
    {
      if (arg)
        {
          /* the following for BCPL pecularities.. */
          if (arg[strlen (arg) - 1] != '\n') strcat (arg, "\n");
        }

      /* no interpreter expansion here, but Arp runs much stabler than 2.0... */
      rc = SyncRun((char *)tmp, (char *)arg, 0, 0);
      err = __ioerr_to_errno (IoErr ());
    }
  else
    {
      BPTR segs;
      char *args;
      struct Segment *res_seg = 0;

      segs = __load_seg (tmp, &args, 0);

      /* check for special cookie */
      if (segs == (BPTR) -2)
	{
	  syscall (SYS_sigsetmask, omask);

	  /* let the shell do the dirty work ;-)) */
	  return system (argline);
	}

      /* also check the resident list, for those that actually don't use rez... */
      if (! segs)
        {
          Forbid ();
          res_seg = FindSegment (tmp, 0, 0);
          if (res_seg)
            {
              /* strange they didn't provide a function for this... */
              if (res_seg->seg_UC >= 0) 
	        res_seg->seg_UC++;
              segs = res_seg->seg_Seg;
              args = 0;
	    }
          Permit ();
        }

      if (segs)
	{
	  char **name;
	  char *orig;
	  char *all_args;
	  
	  /* if __load_seg() set args to something, we have to rebuild our
	   * command line, but really just in that case ;-))
	   */
	  if (args)
	    {
	      int force_quotes = 0;

	      /* now this IS a horrible kludge.. but again, I *NEED* sksh
	       * working, and it only works, if the argument to the -c 
	       * switch is passed quoted... So if the __load_seg code
	       * decided, that this was such a special sksh-script, it 
	       * negates the *arg parameter... shudder... 
	       *
	       * NOTE: This only works for command lines that contain no
	       *       quotes themselves... I don't escape the argument
	       *	   line, I just put a pair of quotes around it!
	       *	   The starting quote is already included in the args
	       *	   string from __load_seg()...
	       */
	      if (((int)args) < 0)
	        {
	          force_quotes = 1;
	          args = (char *) ((-(int)args));
	        }

	      /* make handling easier */
	      if (! arg) arg = "";
	      
	      /* the command we build looks like:
	       * <seg'd command> args arg
	       */
	      
	      all_args = alloca (strlen (args) + 1 + strlen (arg) + 4);
	      strcpy (all_args, args);
	      if (*arg)
	        {
	          strcat (all_args, " ");
	          strcat (all_args, arg);
	        }

	      if (force_quotes)
		strcat (all_args, "\"");  /* no comment... */
	      strcat (all_args, "\n");	  /* neither, this insn't my kludge though.. */

	      /* and finally reassign the commandline to arg */
	      arg = all_args;
	      /* if args was not "", we have to free it, it's from strdup() */
	      if (*args) syscall (SYS_free, args);
	    }
	  else
	    {	
	      /* even if we didn't get any arguments from the expander, we still
	       * need to protect the original arguments ala BCPL ..
	       * Remember that `arg' is a (large enough) alloca() string ;-) */
	      if (arg)
		strcat (arg, "\n");
	      else
		arg = "\n";
	    }

	  /*
	   * Hack to always get the name of the currently executing program
	   * in Xoper
	   */
	  if (CLI)
	    {
	      name = (char **) & CLI->cli_CommandName;
	      orig = *name;
	      /* that's why we incremented tmp before ;-)) */
	      ((unsigned char *)tmp)[-1] = strlen (tmp);
	      /* this is always odd (stack=even + 1), so will chop fine to BPTR */
	      *name = (char *) ((long)tmp >> 2);
	    }
	  else
	    {
	      name = (char **) & me->pr_Task.tc_Node.ln_Name;
	      orig = *name;
	      *name = tmp;
	    }

DP(("RunCommand (.. arg = >%s<, len = %ld)\n", arg, strlen (arg)));
	
	  rc = RunCommand (segs, stack_size, arg, strlen (arg));
          err = __ioerr_to_errno (IoErr ());
	  *name = orig;

	  if (res_seg)
	    {
	      Forbid ();
	      if (res_seg->seg_UC > 0)
		res_seg->seg_UC--;
	      Permit ();
	    }
	  else
	    UnLoadSeg (segs);
	}
      else
	{
	  rc = 20;

          err = __ioerr_to_errno (IoErr ());
        }
    }

  syscall (SYS_sigsetmask, omask);

  if (rc > 128)
    errno = EINTR;
  else
    errno = err;

  return (rc >= 128) ? W_EXITCODE (0, rc & 0x7f) : W_EXITCODE (rc, 0);
}
