/*    $Id: cmd.c,v 1.1 1998/10/27 13:44:46 jap Exp $

 *    Copyright (c) 1998 John Phillips
 *
 *    You may distribute under the terms of the Artistic License
 *
 */

#include "bcnu.h"

extern struct bcnu_agent_def bcnud_agent[];
extern struct bcnu_msg_def bcnud_in;
extern char progname[];
extern char *id, *subver;
extern char starttime[];
extern char buf[], response[];
extern int s, masterok;


bcnu_pipe_init ()
{
  if (pipe (pipefd))
    bcnu_error ("Unable to create pipe");

  bcnu_pipein = pipefd[0];
  bcnu_pipeout = pipefd[1];
  fcntl (bcnu_pipein, F_SETFL, O_NONBLOCK);
}

bcnu_pipe_send (cmd)
     char *cmd;
{
  int bytes;
  char sndbuf[BCNU_MESS];
  sprintf (sndbuf, "%s\n", cmd);
/* printf("sending %s to pipe \n",cmd); */
  bytes = write (bcnu_pipeout, sndbuf, strlen (sndbuf));
  if (bytes < strlen (sndbuf))
    bcnu_error ("Error writing to pipe");
}

bcnu_pipe_read (cmd)
     char *cmd;
{
  int bytes = 0;
  bytes = read (bcnu_pipein, cmd, BCNU_MESS);
  if (bytes <= 0)
    return (0);
  else
    {
      cmd[bytes] = 0;
/*      printf("pid (%d) Got %s [%d bytes]from pipe\n",getpid(),cmd,bytes); */
      return (bytes);
    }

}

bcnu_process_cmd (cmd)
     char *cmd;
{
  char *ptr, *ptrb;
  char cmnd[12], agent[20], option[20];

  int f;
/*  printf ("process got [%s]\n", cmd); */

  ptrb = cmd;

  while (ptr = strchr (ptrb, '\n'))

    {
      *ptr = 0;
/*      printf ("chopper got [%s]\n", ptrb); */
      sscanf (ptrb, "%[^ \n] %[^ \n] %[^ \n]", cmnd, agent, option);
      ptrb = ++ptr;
/*      printf ("parser got [%s] [%s] [%s]\n", cmnd, agent, option); */

      if (strcasecmp (cmnd, BCNU_MSG_AGT_RELOAD) == 0)
	{
	  bcnu_load_agents ();
	}
      else if (strcasecmp (cmnd, "disable") == 0)
	{
	  for (f = 0; f < bcnu_agents_loaded; f++)
	    {
	      if (strcasecmp (agent, bcnud_agent[f].agent_name) == 0)
		{
		  bcnud_agent[f].status = 0;
		  sprintf (workbuf, "disabled %s", bcnud_agent[f].agent_name);
		  bcnu_log (workbuf);
		  break;
		}
	    }
	}

    }
}
