/*
**  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 "sw_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   sw_start_request         (sw_data       *sw); */
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 swid[]   = { HRSWINSTALLEDID };
static gulong swname[] = { HRSWINSTALLEDNAME };
static gulong swtype[] = { HRSWINSTALLEDTYPE };
static gulong swdate[] = { HRSWINSTALLEDDATE };

#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 Software Table plugin.\n");

  menu_location         = g_strdup ("Plugins/");

  menu                  = g_malloc0 (2 * sizeof(GnomeUIInfo));
  menu->type            = GNOME_APP_UI_ITEM;
  menu->label           = g_strdup ("Software");
  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 software\n"
		    "table from.\n\nThe software table can not be loaded.\n"));
      return;
    }
  dbi = (DB_interface *)gl->data;
  if (dbi)
    {
      sw_data    *sw;

      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 software table can not be loaded.\n"));
	  return;
	}
      
      g_print ("Load software table from %s using the %s snmp config.\n", 
	       dbh->dns_name, dbs->name);
      sw          = g_new0 (sw_data, 1);
      sw->rowid   = dbi->rowid;
      if (!gxsnmp_dialog_check ("software_table", NULL))
	{
	  dialog_widget = gxsnmp_sw_dialog_new (sw);
	  if (dialog_widget)
	    {
	      gxsnmp_dialog_add (dialog_widget, "Software Table", NULL, 
				 g_strdup ("Software Table"));
	      sw->dialog = dialog_widget;
	      sw_start_request (sw);
	    }
	}
      
    }
}

/****************************************************************************
 * Start loading the process table from the specified node.
 ***************************************************************************/
gboolean
sw_start_request (sw_data *sw)
{
  DB_interface    *dbi;
  DB_snmp         *dbs;
  GSList	  *objs;
  D_FUNC_START;
  if (!(dbi = g_sqldb_row_find (interface_sqldb, "_rowid", &sw->rowid)))
    {
      notice_dlg (_("No interfaces on the selected host.\n\nSoftware 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"
		    "Software 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"
		    "software table from the host.\n\nSoftware table will not "
		    "be loaded."));
      return FALSE;
    }
  objs = NULL;
  g_pdu_add_oid (&objs, swid, oidlen(swid), SNMP_NULL, NULL);
  g_pdu_add_oid (&objs, swname, oidlen(swname), SNMP_NULL, NULL);
  g_pdu_add_oid (&objs, swtype, oidlen(swtype), SNMP_NULL, NULL);
  g_pdu_add_oid (&objs, swdate, oidlen(swdate), SNMP_NULL, NULL);
  sw->host.domain         = dbi->transport;
  sw->host.rcomm          = dbs->read_c ? g_strdup (dbs->read_c) : "public";
  sw->host.wcomm          = dbs->write_c ? g_strdup (dbs->write_c) : "private";
  sw->host.retries        = dbs->retries;
  sw->host.name           = g_strdup (dbi->address);
  sw->host.status         = 0;
  sw->host.port           = dbs->port;
  sw->host.timeout        = dbs->timeout;
  sw->host.version        = dbs->version;
  
  sw->table               = g_snmp_table_new(&sw->host, objs,
			      error_cb, row_cb, finish_cb, sw);
  g_snmp_table_get(sw->table);
  sw_dialog_set_state (GXSNMP_SW_DIALOG (sw->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];
  sw_data              *sw;
  SNMP_OBJECT          *obj;
  gint                 i;
  gchar                *kludge[6];        /* should do this dynamicly */
  gchar                *ptr;

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

  for (i = 0; i < 4; 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 2: /* Type */
	    if ((ptr = match_strval(obj->syntax.ul[0], hrSWInstalledType)))
	      kludge[i] = g_strdup(ptr);
	    else
	      kludge[i] = g_strdup(buf);
	    break;
	  case 3: /* Date */
            snprintf(buf, sizeof (buf), "%d/%d/%d %d:%d:%d.%d",
		     obj->syntax.uc[2],
		     obj->syntax.uc[3],
		     obj->syntax.uc[0]*256 + obj->syntax.uc[1],
		     obj->syntax.uc[4],
		     obj->syntax.uc[5],
		     obj->syntax.uc[6],
		     obj->syntax.uc[7]);
	    kludge[i] = g_strdup(buf);
	    break;
	  default:
	    kludge[i] = g_strdup(buf);
	}
    }
  gtk_clist_append (GXSNMP_SW_DIALOG(sw->dialog)->clist, kludge);
  D_FUNC_END;
}

static void
finish_cb (gpointer data)
{
  sw_data              *sw;
  D_FUNC_START;
  sw = (sw_data *)data;
  d_print (DEBUG_TRACE, "Done!\n");
  g_snmp_table_destroy(sw->table);
  sw->table   = NULL;
  sw_dialog_set_state (GXSNMP_SW_DIALOG (sw->dialog));
  D_FUNC_END;
}

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

