/*
 * system.c  -  Execute a Mupfel command via _shell_p
 * 23/10/88
 */
 
#include <tos.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

/*
 * MUPFEL_ONLY:
 * 	0 if it should also work with other shells
 * 	1 for checking if Mupfel or MVMERGE are really there
 */
#define MUPFEL_ONLY 1

#define _SHELL_P ((long *)0x4f6L)

#if MUPFEL_ONLY
#define SHELL_OK	(do_sys!=0 && (!strncmp(xbra_id,"XBRAMUPF",8) || !strncmp(xbra_id,"XBRAGMNI",8)))
#else
#define SHELL_OK	(do_sys!=0)
#endif

/*
 * int system(const char *cmd)
 * Executes a command via the shell pointed to by _shell_p.
 * Returns -1 without shell, otherwise
 * the exit code of the executed command/
 * The internal Mupfel routine expects the pointer to the command line
 * on the stack und returns the exit code of the executed
 * command in register D0.W.
 */
int system(const char *cmd)
{
	/* Pass parameter on the stack! */
	int cdecl (*do_sys)(const char *cmd);
	char *xbra_id;
	long oldssp;

	oldssp = Super(0L);
	do_sys = (void (*))*_SHELL_P;
	Super((void *)oldssp);
	xbra_id = (char *)((long)do_sys - 12);
	
	if (cmd==NULL)
		return SHELL_OK;

	if (SHELL_OK)
		return do_sys(cmd);
	else
		return -1;
}

/*
 * Testprogram for system().
 * A command line is put together consisting of all arguments and passed
 * to Mupfel via system().
 */
int main(int argc,char **argv)
{
	int i, ex_code;
	char str[256];
	
	printf("Shell status: %d\n",system(NULL));
	*str = '\0';
	for (i=1; i<argc; ++i)
	{
		strcat(str,argv[i]);
		strcat(str," ");
	}
	printf("system(%s)\n",str);
	ex_code = system(str);
	if (ex_code == -1)
		printf("No Mupfel?!?\n");
	else
		printf("Returncode %d\n",ex_code);
	return 0;
}
