/*
 * GPR
 * Copyright (C) 2000 CompuMetric Labs, Inc.
 *
 * For more information contact:
 *        Thomas Hubbell
 *        CompuMetric Labs, Inc.
 *        5920 Grelot Road, Suite C-2
 *        Mobile, AL 36609
 * 
 * Voice: (334) 342-2220
 *   Fax: (334) 343-2261
 * Email: thubbell@compumetric.com
 *   Web: http://www.compumetric.com
 *
 * 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.
 *    
 *        File: Main.c
 * 
 * Description: Main program
 */

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

#include "unistd.h"
#include <stdlib.h>
#include <string.h>

#ifdef USE_GNOME
#include <gnome.h>
#else
#include <gtk/gtk.h>
#include <popt.h>
#endif

#include <gettext.h>
#include <sys/stat.h>

#include "interface.h"
#include "support.h"
#include "tab_categories.h"

/* popt variables and structs */
static char *printer = NULL;
static char *jobname = NULL;
static int remove_job = FALSE;
       int debug_on = FALSE;
static int no_run = FALSE;
static int ppdfilt = 1;


/*
  MLP: This is the "tab categories" pointer. Need
  a better way to access it than a global. 
*/
ptrTab *globalTabList = NULL;

char * cmdname = NULL;

int main(int argc, char **argv)
{
  GtkWidget *gpr_main_window;	/* The main gpr window */
  GtkWidget *gpr_inst_options_window;	/* the installable options
					   window */
  ppd_struct *ppd;	/* local copy of the ppd structure */

  const char **args;	/* leftover command-line arguments */

  int i;		/* argument index */
  char tf_path[64];	/* temporary file pathname */
  int tfd = -1;		/* temporary file descriptor */
  FILE *tmpf = 0;	/* temporary file */
  char curr_line[200];	/* the current line of input from stdin */
  struct stat info;	/* file info, used to see if file is piped 
			   from an app */


  cmdname = "lpr";
  //Mennucc: in Debian, gpr may divert lpr to a script that calls gpr
  //   this command line avoids looping
  {
    struct stat buf;
    if ( 0==stat("/usr/bin/lpr.not.gpr", &buf ) ) {
      cmdname = "/usr/bin/lpr.not.gpr";
    }
  }
  // Mennucc: this seems to be an obvious error
  if (0==strcmp(argv[0], "lpr")) {
    if (getenv("DISPLAY") == NULL) {
      char **vars = malloc(sizeof(char *) * (argc + 1));
      vars[argc] = NULL;
      for (i = 0; i < argc; i++)
	vars[i] = argv[i];
      execvp("/usr/bin/lpr.not.gpr", vars);
      // exec failed
      perror("gpr");
      exit(1);
    }
  }


  ppd = malloc(sizeof(ppd_struct));
  memset(ppd, 0, sizeof(ppd_struct));


const struct poptOption options[] = {
  {
    "printer",'P',POPT_ARG_STRING,&printer,0,
    _("Specify a destination printer"),NULL
  },{
    "debug",'d',POPT_ARG_NONE,&debug_on,0,
    _("Enable debugging output"),NULL
  },{
    "jobname",'J',POPT_ARG_STRING,&jobname,0,
    _("lpr option: Job name to print on burst page"),NULL
  },{
    "remove",'r',POPT_ARG_NONE,&remove_job,0,
    _("lpr option: Remove the files upon completion of spooling"),NULL
  },{
    "norun",'n',POPT_ARG_NONE,&no_run,0,
    _("gpr option: Print the command line rather than executing the command"),
    NULL
  },{
    "ppdfilt",'p',POPT_ARG_INT,&ppdfilt,0,
    _("gpr option: Use ppdfilt: 0 = Never, 1 = Always, 2 = with non-default PPD"),
    NULL
  },POPT_AUTOHELP
  {
    NULL,'\0',0,NULL,0,NULL,NULL
  }
};

  //seems this is useless
 gtk_set_locale();

  
  //gnome_init("gpr", VERSION, argc, argv);
#ifdef USE_GNOME
  gnome_init_with_popt_table("gpr", VERSION, argc, argv, options, 0, &pctx);
#else
  if(! (gtk_init_check(&argc, &argv))) 
    { g_error(_("error initializing GTK")) ;     return 1; }
#endif


#ifdef ENABLE_NLS
  bindtextdomain(PACKAGE, PACKAGE_LOCALE_DIR);
#if GTK_MAJOR_VERSION >= 2
  /* Mennucc: from here on, all messages will be translated before
     they are passed to GTK, that is, Pango, so they must be UTF-8.
     Thanks to Thomas Huriaux (see http://bugs.debian.org/361260 ) */
  bind_textdomain_codeset(GETTEXT_PACKAGE, "UTF-8");
  /* note that this means that any translated  message that may be written to
     the terminal will be UTF-8 as well!
     Should use g_set_printerr_handler () and iconv to translate back...
  */
#warning "FIX UTF OUTPUT"
#endif
  textdomain(PACKAGE);
#endif

#if HAVE_POPT_H
  {
    poptContext pctx;	/* the popt context */
    pctx= poptGetContext("gpr",argc,argv,
			 options, //const struct poptOption * options,
			 0);//int flags);
    
    int val;  
    while( (val= poptGetNextOpt(pctx)) >=0) 
      printf("%d  ",val); 
    if(val < -1 )    { 
      char * msg1=poptBadOption(pctx, POPT_BADOPTION_NOALIAS);
      char * msg2=poptStrerror(val);
      fprintf(stderr,"%s: %s\n",msg1,msg2) ;
      //g_error(_("error %d parsing command line parameters"),val) ;
      return 1;}
    
    args = poptGetArgs(pctx);
  

  if (args != NULL) {
    i = 0;
    while (args[i] != NULL) {
      ppd->file_to_print = g_strdup(args[i]);
      if (no_run)    printf("gpr: printing '%s' \n",args[i]);
      ++i;
    }
    /* ensures we have the correct path to the file on the
       command_line */
    if (!g_path_is_absolute(ppd->file_to_print)) {
      ppd->file_to_print =
	g_strconcat(g_get_current_dir(), "/",
		    ppd->file_to_print, NULL);
    }
    if(i>1) g_warning("gpr prints only one file at a time (sorry about that)");
  }
 poptFreeContext(pctx);
  }
#else
  if(argc>1) g_warning(" compile gpr with libpopt to be able to use command line parameters");
#endif

  if (no_run)
    ppd->debug_flag = 1;

  /* 
   * Very simple command-line option parsing routine
   * Will expand and make more robust as we add more options.
   */
  if (printer)
    ppd->printer_name = g_strdup(printer);
  else {
    printer = g_getenv("PRINTER");
    if (printer)
      ppd->printer_name = g_strdup(printer);
  }

  if (remove_job) {
    if (ppd->lpr_opts)
      ppd->lpr_opts = g_strconcat(ppd->lpr_opts, "-r ", NULL);
    else
      ppd->lpr_opts = g_strconcat("-r ", NULL);
  }

  if (debug_on)
    ppd->debug_flag = 1;

  ppd->ppdfilt = ppdfilt;

  ppd->spooler = get_spooler_type_debian();
  if( ppd->spooler == SPOOLER_CUPS && ppdfilt) 
    cmdname=g_strconcat(cmdname," -o raw",NULL);


  /* add -P for printer name*/
  cmdname=g_strconcat(cmdname," -P",NULL);

  /*-----------------------------------------------------------------
    MLP: Parse the tab categories file, at its expected location.
  -----------------------------------------------------------------*/
#if HAVE_XML
  globalTabList = tab_parse_xml_file ("/usr/share/gpr/tabs/categories.xml");
#endif

  /* 
   * check to see if file is being piped in from an app or from command-line
   * if so, copy to a temp file
   */
  fstat(0, &info);
  if (S_ISFIFO(info.st_mode) || S_ISREG(info.st_mode)) {
    strcpy(tf_path, "/tmp/gpr-XXXXXX");
    if ((tfd = mkstemp(tf_path)) >= 0) {
      ppd->file_to_print = g_strdup(tf_path);
      tmpf = fdopen(tfd, "w+");
      while (fgets(curr_line, sizeof(curr_line), stdin)
	     != NULL) {
	fputs(curr_line, tmpf);
      }
      fclose(tmpf);
    }
  }

  gpr_inst_options_window = create_gpr_inst_options_window(ppd);

  gpr_main_window = create_gpr_main_window(ppd, gpr_inst_options_window);
  gtk_widget_show(gpr_main_window);

  gtk_main();
 
  /*A Mennucc: clean up is called if and only if the program is really closed*/
  clean_up(NULL, ppd);
  
  free(ppd);
  ppd = NULL;

  return 0;
}
