// Copyright, 2001-2003, Astra Network Inc.  All Rights Reserved

// This source code has been published by Astra Network Inc. However, any
// use, reproduction, modification, distribution or transfer of this
// software, or any software which includes or is based upon any of this
// code, is only permitted if expressly authorized by a written license
// agreement from Astra. Contact your Astra representative directly for
// more information.


#include <olmod.h>
#include <unistd.h>
#ifdef QNX4
# include <process.h>
#endif

typedef struct sh_data_s
{
  char *shell;
}
sh_data_t;


olmod_error_t
sh_module_init ()
{
  return kMod_OK;
}

olmod_blackbox_t *
sh_module_inst (pid_t /*@unused@ */ process,
		olmod_arglist_t * static_args)
{
  sh_data_t *blackbox;

  if (!(blackbox = (sh_data_t *) malloc (sizeof (sh_data_t))))
    {
      printf ("mod_sh: malloc failed\n");
      return (void *) -1;
    }

  blackbox->shell = malloc (strlen (static_args[0]) + 1);
  if (blackbox->shell == NULL)
    {
      printf ("mod_sh: malloc failed\n");
      return (void *) -1;
    }
  strcpy (blackbox->shell, static_args[0]);

  return blackbox;
}

olmod_error_t
sh_module_set (olmod_blackbox_t /*@unused@ */  * data,
	       int64_t /*@unused@ */ var)
{
  return kMod_OK;
}

int64_t
sh_module_get (olmod_blackbox_t /*@unused@ */  * data,
	       olmod_arglist_t * dynamic_args)
{
  pid_t pid;
  sh_data_t *blackbox = (sh_data_t *) data;

  if ((pid = fork ()) == 0)
    {				/* Child process */
      setsid ();
      if ((execl (blackbox->shell, blackbox->shell, "-c",
		  (char *) dynamic_args[0], NULL)) == -1)
	return LTOQ (0L);
    }
  return LTOQ ((long) pid);
}

void
sh_module_deinst (olmod_blackbox_t * data)
{
  free (((sh_data_t *) data)->shell);
  free (data);
}

void
sh_module_deinit ()
{
}
