/*
**  GXSNMP -- An snmp management application
**  Copyright (C) 1998 Gregory McLean
**
**  This program is free software; you can redistribute it and/or modify
**  it under the terms of the GNU General Public License as published by
**  the Free Software Foundation; either version 2 of the License, or
**  (at your option) any later version.
**
**  This program 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 General Public License for more details.
**
**  You should have received a copy of the GNU General Public License
**  along with this program; if not, write to the Free Software
**  Foundation, Inc.,  59 Temple Place - Suite 330, Cambridge, MA 02139, USA.
**
**  plugin-sample.c -- A sample plugin, it don't do anything but its useful
**                     for testing.
*/

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <gnome.h>
#include "menus.h"
#include "plugins.h"
#include "main.h"
#include "gxsnmp_map.h"
#include "gxsnmp_host.h"
#include "process_dialog.h"
#include "host_resources.h"

#include "debug.h"

extern GtkWidget * host_popup_menu;
extern gxsnmp * app_info;

/****************************************************************************
 * Forward references
 ***************************************************************************/
static void       menu_callback            (GtkWidget     *widget,
					    gpointer      data);
/*static gboolean   process_start_request   (ps_data       *ps); */
static void       row_cb                   (GHashTable    *objs,
                                            guint         indlen,
                                            gpointer      data);
static void       error_cb                 (gpointer      data);
static void       finish_cb                (gpointer      data);
/****************************************************************************
 *  Static data
 ***************************************************************************/

static gchar * menu_location;

static gulong runindex[]  = { HRSWRUNINDEX };
static gulong runname[]   = { HRSWRUNNAME };
static gulong runpath[]   = { HRSWRUNPATH };
static gulong runparms[]  = { HRSWRUNPARAMETERS };
static gulong runtype[]   = { HRSWRUNTYPE };
static gulong runstatus[] = { HRSWRUNSTATUS };

#define oidlen(val) (sizeof(val)/sizeof(gulong))

/******************************************************************************
**
**  The plugin load routine
**
**  This function is invoked at the very start of GXSNMP.  It should
**  set one or more of the following flags:
**
**  PLUGIN_DATABASE	-- for plugins that provide a database service
**  PLUGIN_COLLECTOR	-- for plugins that do not require GTK services
**  PLUGIN_APPLICATION	-- for plugins that require GTK services
**
**  The flags determine at what point the start function is called during
**  initialization.  The database plugins need to be started before the
**  database is read in (for obvious reasons), and the collector and 
**  application plugins are not started until the database is completely
**  read in and set up.
**
******************************************************************************/

gint
load_plugin (PluginData * pd)
{
  pd->type = PLUGIN_APPLICATION;
  return 0;
}

/****************************************************************************
 *
 *  The plugin unload routine
 *
 *  This function is invoked during the shutdown callback in main.c
 *  It should free any storage the plugin might have allocated, and
 *  generally clean itself up.
 *
 ***************************************************************************/
void
unload_plugin (PluginData * pd)
{
}

/******************************************************************************
**
**  The plugin start routine
**
**  This function is invoked during initialization.  It should perform      
**  initialization and start the plugin running.
**
**  Included here is sample code to install the plugin in the 'plugins' menu.
**  A collector-only plugin would NOT install a menu entry, and would not
**  have a menu callback routine (below).
**
******************************************************************************/

gint 
start_plugin (PluginData * pd)
{
  GnomeUIInfo   * menu;
  g_print ("Starting ProcessTable plugin.\n");

  menu_location         = g_strdup ("Plugins/");

  menu                  = g_malloc0 (2 * sizeof(GnomeUIInfo));
  menu->type            = GNOME_APP_UI_ITEM;
  menu->label           = g_strdup ("Process Table");
  menu->hint            = NULL;
  menu->moreinfo        = menu_callback;       /* Menu activation cb routine */
  menu->user_data       = NULL;                /* User data for the callback */
  menu->unused_data     = NULL;                /* Reserved for future use */
  menu->pixmap_type     = GNOME_APP_PIXMAP_STOCK;
  menu->pixmap_info     = GNOME_STOCK_MENU_BLANK;
  menu->accelerator_key = 0;
  (menu + 1)->type      = GNOME_APP_UI_ENDOFINFO;

  gxsnmp_add_to_host_popup (menu);
 
  return 0;
}

/******************************************************************************
**
**  Menu callback routine for the plugin
**
**  This function is invoked when the user selects the plugin from the
**  plugins menu.
**
******************************************************************************/

static void
menu_callback (GtkWidget * widget, gpointer data)
{
  GtkWidget       *dialog_widget;
  DB_host         *dbh;
  DB_interface    *dbi;
  DB_snmp         *dbs;
  GList           *gl;
  GXsnmp_map_item *item;
  
  item = GXSNMP_MAP_ITEM (data);
  dbh = item->DB_graph->DB_host;
  if (!(gl = dbh->DB_interfaces))
    {
      notice_dlg (_("The selected host has no interfaces defined on it,\n"
		    "there must be at least one defined to load the process\n"
		    "table from.\n\nThe process table can not be loaded.\n"));
      return;
    }
  dbi = (DB_interface *)gl->data;
  if (dbi)
    {
      ps_data    *ps;

      dbs = g_sqldb_row_find (snmp_sqldb, "_rowid", &dbi->snmp);
      if (!dbs)
	{
	  notice_dlg (_("The selected host has interfaces defined, but\n"
			"there appears to be a problem with the SNMP\n"
			"configuration for the interface.\n"
			"\nThe process table can not be loaded.\n"));
	  return;
	}
      
      g_print ("Load process table from %s using the %s snmp config.\n", 
	       dbh->dns_name, dbs->name);
      ps          = g_new0 (ps_data, 1);
      ps->rowid   = dbi->rowid;
      if (!gxsnmp_dialog_check ("process_table", NULL))
	{
	  dialog_widget = gxsnmp_process_dialog_new (ps);
	  if (dialog_widget)
	    {
	      gxsnmp_dialog_add (dialog_widget, "Process Table", NULL, 
				 g_strdup ("Process Table"));
	      ps->dialog = dialog_widget;
	      process_start_request (ps);
	    }
	}
      
    }
}

/****************************************************************************
 * Start loading the process table from the specified node.
 ***************************************************************************/
gboolean
process_start_request (ps_data *ps)
{
  DB_interface    *dbi;
  DB_snmp         *dbs;
  GSList	  *objs;
  D_FUNC_START;
  if (!(dbi = g_sqldb_row_find (interface_sqldb, "_rowid", &ps->rowid)))
    {
      notice_dlg (_("No interfaces on the selected host.\n\nProcess Table will"
		  "not be loaded.\n"));
      return FALSE;
    }
  if (!(dbs = (DB_snmp *)dbi->DB_snmp))
    {
      notice_dlg (_("Interface defined but no snmp configuration found.\n\n"
		    "Process table will not be loaded."));
      return FALSE;
    }
  if (!dbi->address)
    {
      notice_dlg (_("There was no address associated with this interface.\n"
		    "An address must be specified in order to load the\n"
		    "process table from the host.\n\nProcess table will not be "
		    "loaded."));
      return FALSE;
    }
  objs = NULL;
  g_pdu_add_oid (&objs, runindex, oidlen(runindex), SNMP_NULL, NULL);
  g_pdu_add_oid (&objs, runname, oidlen(runname), SNMP_NULL, NULL);
  g_pdu_add_oid (&objs, runpath, oidlen(runpath), SNMP_NULL, NULL);
  g_pdu_add_oid (&objs, runparms, oidlen(runparms), SNMP_NULL, NULL);
  g_pdu_add_oid (&objs, runtype, oidlen(runtype), SNMP_NULL, NULL);
  g_pdu_add_oid (&objs, runstatus, oidlen(runstatus), SNMP_NULL, NULL);
  ps->host.domain         = dbi->transport;
  ps->host.rcomm          = dbs->read_c ? g_strdup (dbs->read_c) : "public";
  ps->host.wcomm          = dbs->write_c ? g_strdup (dbs->write_c) : "private";
  ps->host.retries        = dbs->retries;
  ps->host.name           = g_strdup (dbi->address);
  ps->host.status         = 0;
  ps->host.port           = dbs->port;
  ps->host.timeout        = dbs->timeout;
  ps->host.version        = dbs->version;
  
  ps->table               = g_snmp_table_new(&ps->host, objs,
			      error_cb, row_cb, finish_cb, ps);
  g_snmp_table_get(ps->table);
  process_dialog_set_state (GXSNMP_PROCESS_DIALOG (ps->dialog));
  D_FUNC_END;
  return TRUE;
}
/****************************************************************************
 * Helper function 
 ***************************************************************************/
static gchar*
match_strval(guint32 val, const value_string *vs) {
  gint i = 0;

  while (vs[i].strptr) {
    if (vs[i].value == val)
      return(vs[i].strptr);
    i++;
  }
  return(NULL);
}

/****************************************************************************
 * SNMP Data callback
 ***************************************************************************/
static void
row_cb (GHashTable *objs, guint indlen, gpointer data)
{
  gchar                buf[512];
  ps_data              *ps;
  SNMP_OBJECT          *obj;
  gint                 i;
  gchar                *kludge[6];        /* should do this dynamicly */
  gchar                *ptr;

  D_FUNC_START;
  ps = (ps_data *)data;
  d_print (DEBUG_DUMP, "Completed request %x\n", (guint)ps->table);

  for (i = 0; i < 6; i++)
    {
      obj = (SNMP_OBJECT *) g_hash_table_lookup(objs, &i);
      if (!obj)
	{
	  g_warning("Problems getting obj pointer. Smells fishy here...\n");
	  kludge[i] = g_strdup("");
	  continue;
	}
      g_snmp_printf (buf, sizeof (buf), obj);
      switch(i)
	{
	  case 4: /* Type */
	    if ((ptr = match_strval(obj->syntax.ul[0], hrSWRunType)))
	      kludge[i] = g_strdup(ptr);
	    else
	      kludge[i] = g_strdup(buf);
	    break;
	  case 5: /* Status */
	    if ((ptr = match_strval(obj->syntax.ul[0], hrSWRunStatus)))
	      kludge[i] = g_strdup(ptr);
	    else
	      kludge[i] = g_strdup(buf);
	    break;
	  default:
	    kludge[i] = g_strdup(buf);
	}
    }
  gtk_clist_append (GXSNMP_PROCESS_DIALOG(ps->dialog)->clist, kludge);
  D_FUNC_END;
}

static void
finish_cb (gpointer data)
{
  ps_data              *ps;
  D_FUNC_START;
  ps = (ps_data *)data;
  d_print (DEBUG_TRACE, "Done!\n");
  g_snmp_table_destroy(ps->table);
  ps->table   = NULL;
  process_dialog_set_state (GXSNMP_PROCESS_DIALOG (ps->dialog));
  D_FUNC_END;
}

/****************************************************************************
 * SNMP timeout 
 **************************************************************************/
static void
error_cb (gpointer data)
{
  ps_data      *ps;
  D_FUNC_START;
  g_return_if_fail (data != NULL);
  ps = (ps_data *)data;
  d_print (DEBUG_DUMP, "Request timed out %x\n", (guint)ps->table);
  g_snmp_table_destroy(ps->table);
  ps->table   = NULL;
  D_FUNC_END;
}

