/* Jungle Monkey Multicast Search Protocol Client
 * Copyright (C) 2000-2001  The Regents of the University of Michigan
 *
 * 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, Boston, MA  02111-1307  USA
 */

#include "config.h"

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#include <errno.h>
#include <unistd.h>
#include <time.h>
#include <sys/types.h>
#include <signal.h>

#ifdef JM_ENABLE_GNOME
#include <popt-gnome.h>
#else
#include <popt.h>
#endif

#include "jmintl.h"
#include "util/util.h"

#include "jmmsp.h"
#include "jmmsp_debug.h"
#include "jmmsp_cache.h"
#include "jmmsp_search.h"
#include "jmmsp_vfs.h"




static void sig_int_cb (int ignore);

static void search_cb (JMMSPSearch* search, JMMSPSearchID id, 
		      const JMMSPReply* reply, gpointer user_data);
static void error_cb (JMMSP* jmmsp, gpointer user_data);




/* ******************** */
/* Globals		*/

static int   		verbose = 0;

static BPeer*		bpeer;

static JMMSP*		jmmsp;
static JMMSPCache*	jmmsp_cache;
static JMMSPVFS*	jmmsp_vfs;
static JMMSPSearch*	jmmsp_search;

static JMMSPSearchID 	search_id;

extern int 		btp_debug_level;
extern unsigned int 	btp_debug_flags;


int
main(int argc, char* argv[])
{
  const gchar* url = NULL;
  GMainLoop* main_loop;
  const gchar* keyword = NULL;
  const gchar* file = NULL;
  gboolean do_cache = FALSE;

  struct poptOption jm_options[] = 
  {
    {"help", 'h', POPT_ARG_NONE, NULL, 1, 
     "Show this help message", NULL},
    {"usage", '\0', POPT_ARG_NONE, NULL, 2, 
     "Display brief usage message", NULL},
    {"version", 0, POPT_ARG_NONE, NULL, 3,
     "Output verson information and exit", NULL},
    {"verbose", 'v', POPT_ARG_NONE, &verbose, 0,
     "Print lots of stuff", NULL},

    {"keyword", 'k', POPT_ARG_STRING, &keyword, 0,
     "Keyword", "KEYWORD"},
    {"cache", '\0', POPT_ARG_NONE, &do_cache, 0,
     "Cache replies", NULL},

    {NULL, '\0', 0, NULL, 0, NULL, NULL}
  };

  poptContext ctx;
  int rc;
  int exit_status = EXIT_SUCCESS;


  /* ******************** */
  /* Initialize NLS 	  */
#ifdef ENABLE_NLS
  {
/*      gtk_set_locale(); */
    bindtextdomain (PACKAGE, LOCALEDIR);
    textdomain (PACKAGE);
  }
#endif

  /* ******************** */
  /* Parse command line	  */

  ctx = poptGetContext(NULL, argc, (const char**) argv, jm_options, 0);
  poptSetOtherOptionHelp(ctx, _("[OPTION]... [URL] [FILES]..."));

  while ((rc = poptGetNextOpt(ctx)) > 0)
    {
      switch (rc)
	{
	case 1:	  goto help;	  break;
	case 2:	  goto usage;	  break;
	case 3:   goto version;	  break;
	}
    }

  url = poptGetArg(ctx);
  if (url == NULL)
    {
      g_print ("*** You must specify a URL.\n");
      goto usage;
    }

  /* Catch SIGINT */
  signal (SIGINT, sig_int_cb);

  /* ******************** */
  /* Create bpeer	  */

/*    btp_debug_level = 1; */
/*    btp_debug_flags = 0xFFFF; */
/*    jmmsp_debug_flags = 0xffff; */

  bpeer = b_peer_new ("ask.eecs.umich.edu", NULL, FALSE);
  g_assert (bpeer);
  g_print ("BTP open at %s:%d\n", bpeer->hostname, bpeer->port);

  /* ******************** */
  /* Join/create jmmsp    */

  if (!strncmp(url, "jmmsp://", sizeof("jmmsp://")-1))		/* JOIN */
    {
      GURL* gurl;

      gurl = gnet_url_new (url);
      if (gurl == NULL)
	{
	  g_print ("*** Malformed URL: %s\n", url);
	  goto usage;
	}

      jmmsp = jmmsp_join (bpeer, gurl);
      if (!jmmsp)
	{
	  fprintf (stderr, "%s: Could not join group %s\n", argv[0], url);
	  exit (EXIT_FAILURE);
	}

      g_print ("Joined %s\n", url);
    }
  else
    {
      jmmsp = jmmsp_create (bpeer, url);	/* CREATE */
      if (!jmmsp)
	{
	  fprintf (stderr, "%s: Could not join group %s\n", argv[0], url);
	  exit (EXIT_FAILURE);
	}

      g_print ("Created jmmsp://%s:%d/%s\n", 
	       bpeer->hostname, bpeer->port, url);

    }
  jmmsp->error_func = error_cb;


  /* Create Cache */
  if (do_cache)
    {
      jmmsp_cache = jmmsp_cache_new ();
      jmmsp_cache_set_policy (jmmsp_cache, JMMSP_CACHE_SIZE_DEFAULT, 
			      JMMSP_CACHE_TIMEOUT_DEFAULT);
      jmmsp_add_handler (jmmsp, (JMMSPHandler*) jmmsp_cache);
    }

  /* Create VFS */
  jmmsp_vfs = jmmsp_vfs_new ();
  while ((file = poptGetArg(ctx)) != NULL)
    {
      GURL* dummy_url;

      dummy_url = gnet_url_new_fields ("http", "localhost", 0, file);
      jmmsp_vfs_add (jmmsp_vfs, file, dummy_url, 0);
    }
  jmmsp_add_handler (jmmsp, (JMMSPHandler*) jmmsp_vfs);

  /* Create search */
  jmmsp_search = jmmsp_search_new ();
  jmmsp_add_handler (jmmsp, (JMMSPHandler*) jmmsp_search);
  if (keyword)
    {
      search_id = jmmsp_search_query (jmmsp_search, keyword, search_cb, NULL);
      g_assert (search_id);
    }


  poptFreeContext(ctx);


  /* ******************** */
  /* Start the main loop  */

  main_loop = g_main_new(FALSE);
  g_main_run(main_loop);

  exit(EXIT_SUCCESS);

 usage:
  poptPrintUsage(ctx, stdout, 0);
  exit(exit_status);

 help:
  g_print (_("`jmmspclient' - Jungle Monkey Multicast Search Protocol Client\n"));
  poptPrintHelp(ctx, stdout, 0);
  g_print (_("\n"
	     "Report bugs to <jm-dev@umich.edu>\n"));
  exit(exit_status);

 version:
  g_print (_("jmmspclient %s\n"
	     "Written by David A. Helder\n"
	     "\n"
	     "Copyright (C) 2000-2001 The Regents of the University of Michigan\n"
	     "This is free software; see the source for copying conditions.  There is NO\n"
	     "warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"),
	     VERSION);
  exit(exit_status);
}


/* **************************************** */


static void
sig_int_cb (int ignore)
{
  /* Reset signal handler */
  signal (SIGINT, SIG_DFL);

  /* Delete stuff */
  if (jmmsp_search)
    {
      if (search_id)
	jmmsp_search_cancel (jmmsp_search, search_id);

/*        jmmsp_search_delete (jmmsp_search); */
    }

  if (jmmsp_vfs)
    jmmsp_vfs_delete (jmmsp_vfs);

  if (jmmsp_cache)
    jmmsp_cache_delete (jmmsp_cache);

  if (jmmsp)
    {
      fprintf (stderr, "is up = %d\n", jmmsp_is_up (jmmsp));
      jmmsp_delete (jmmsp);
    }

  exit (EXIT_SUCCESS);
}


static void
search_cb(JMMSPSearch* search, JMMSPSearchID id, 
	  const JMMSPReply* reply, gpointer user_data)
{
  if (reply)
    {
      gchar* url_str;

      url_str = gnet_url_get_nice_string (reply->url);
      g_print ("JMMSP Match: %s, %s, %d\n", reply->name, url_str, reply->length);
      g_free (url_str);
    }
  else
    {
      g_print ("JMMSP Search error.\n");
      search_id = NULL;
    }
}


static void
error_cb (JMMSP* jmmsp, gpointer user_data)
{
  g_print ("JMMSP Error\n");
}


syntax highlighted by Code2HTML, v. 0.9.1