/*
Copyright (c) 2003-2005, Dirk Krause
All rights reserved.

Redistribution and use in source and binary forms,
with or without modification, are permitted provided
that the following conditions are met:

* Redistributions of source code must retain the above
  copyright notice, this list of conditions and the
  following disclaimer.
* Redistributions in binary form must reproduce the above 
  opyright notice, this list of conditions and the following
  disclaimer in the documentation and/or other materials
  provided with the distribution.
* Neither the name of the Dirk Krause nor the names of
  its contributors may be used to endorse or promote
  products derived from this software without specific
  prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
DAMAGE.
*/

#include <dk.h>
#include <dksf.h>

#include "png2pdf.h"

#line 42 "png2pdfm.ctr"



static int
isdir DK_P1(char *,fn)
{
  int back = 0;
  dk_stat_t st;
  
  if(dkstat_get(&st, fn)) {
    if((dkstat_filetype(&st) & (~DK_FT_SYMLINK)) == DK_FT_DIR) {
      back = 1;
    }
  }
  
  return back;
}



/* ********************************************************************* */
/* *                                                                   * */
/* *   Check whether we have to run silently or as a filter.           * */
/* *                                                                   * */
/* ********************************************************************* */

#line 63 "png2pdfm.ctr"

static void
silence_check DK_P4(int,argc,char **,argv,int *,rs,int *,rf)
{
  char *filename, *ptr, **lfdptr; int i; int fn; int isd;
  
  lfdptr = argv; lfdptr++; i = 1; fn = 0; isd = 0;
  filename = NULL;
  fn = 0;
  while(i < argc) {
    ptr = *lfdptr;
    if(*ptr == '-') {
      ptr++;
      switch(*ptr) {
        case 'p': case 'm': {
	  ptr++;
	  if(!(*ptr)) {
	    lfdptr++; i++;
	  }
	} break;
      }
    } else {
      fn++;
      filename = ptr;
      
    }
    lfdptr++; i++;
  }
  if(fn < 2) { 
    if(fn == 1) {	
      if(filename) {	
        if(dksf_must_expand_filename(filename)) {
	  if(rf) { *rf = 1; }		
	} else {	
	  if(!isdir(filename)) {	
	    if(rf) { *rf = 1; }		
	  }
	}
      } else {
        if(rf) { *rf = 1; }		
      }
    } else {
      if(rf) { *rf = 1; }		
    }
  } 
}


static int
run_for_filenames DK_P3(Png2PdfCmd *,c,char *,i,char *,o)
{
  int back = 0;
  
  if(c->a) {					
    c->inf = dkapp_fopen(c->a, i, "rb");
    if(c->inf) {				
      c->realfilename = dksf_get_last_filename(i);
      if(o) {					
        c->of = dkapp_fopen(c->a, o, "wb");
	if(c->of) {				
	  back = png2pdf_for_files(c);
	  fclose(c->of); c->of = NULL;
	} else {				
	  dkapp_err_fopenw(c->a, o);
	}
      } else {					
        c->of = stdout;
	dksf_set_file_binary(stdout);
	back = png2pdf_for_files(c);
	c->of = NULL;
      }
      fclose(c->inf); c->inf = NULL;
      c->realfilename = NULL;
    } else {					
      dkapp_err_fopenr(c->a, i);
    }
  } else {					
    c->inf = dksf_fopen(i, "rb");
    if(c->inf) {					
      if(o) {					
        c->of = dksf_fopen(o, "wb");
	if(c->of) {				
	  back = png2pdf_for_files(c);
	  fclose(c->of); c->of = NULL;
	} else {				
	}
      } else {					
        c->of = stdout;
	dksf_set_file_binary(stdout);
	back = png2pdf_for_files(c);
	c->of = NULL;
      }
      fclose(c->inf); c->inf = NULL;
    } else {					
    }
  } 
  return back;
}



static int
source_newer DK_P3(Png2PdfCmd *,c,char *,src,char *,dst)
{
  int back = 0;
  dk_stat_t st1, st2;
  char *c1, *c2;
  int ft;
  
  if(dkstat_get(&st1, src)) {	
    back = 1;
    if(dkstat_get(&st2, dst)) {	
      ft = dkstat_filetype(&st2);
      if((ft & (~DK_FT_SYMLINK)) == DK_FT_REG) {
        c1 = dkstat_mtime(&st1);
	c2 = dkstat_mtime(&st2);	
	
	if(strcmp(c1,c2) > 0) {
	  back = 1;
	} else {
	  back = 0;
	}
      } else {			
        back = 0;
	/* ##### ERROR: destination no regular file */
      }
    } else {			
    }
  } else {			
  } 
  return back;
}



static int
is_png DK_P1(char *,n)
{
  int back = 0;
  char *suffix;
  
  suffix = dksf_get_file_type_dot(n);
  if(suffix) {		
#if DK_HAVE_FNCASEINS
    if(dkstr_casecmp(suffix, ".png") == 0) {
    			
      back = 1;
    }
#else
    if(strcmp(suffix, ".png") == 0) {
    			
      back = 1;
    }
#endif
  } 
  return back;
}


static int
run_for_directory  DK_P1(Png2PdfCmd *,c)
{
  int back = 0;
  int ft;
  char *ofbuffer, *in, *ins, *suffix;
  unsigned long mpl;
  dk_dir_t *dirptr;
  mpl = dksf_get_maxpathlen();
  ofbuffer = dk_new(char,mpl);
  if(ofbuffer) {		
    dirptr = dkdir_open(c->inputfilename);
    if(dirptr) {	
      back = 1;
      while(dkdir_next(dirptr)) {	
        in = dkdir_get_fullname(dirptr);
	if(in) {	
          ins = dkdir_get_shortname(dirptr);
	  if(ins) {	
	    if(strcmp(ins, ".") && strcmp(ins, "..")) { 
	      ft = dkdir_filetype(dirptr); 
	      if((ft & (~DK_FT_SYMLINK)) == DK_FT_REG) { 
	        if(is_png(in)) {		
		  /*
		    + 3 because in worst case we have to replace
		    filename. by filename.pdf
		  */
		  if((strlen(in) + 3) < mpl) {	
		    strcpy(ofbuffer, in);
		    suffix = dksf_get_file_type_dot(ofbuffer);
		    if(suffix) {		
		      strcpy(suffix, ".pdf");
		      ft = 1;
		      if((c->options) & PNG2PDF_OPT_MAKE) {
		      	
		        ft = source_newer(c, in, ofbuffer);
		      }
		      if(ft) {			
		        if((c->a) && (c->msgptr)) {
			  char *msgptr[3];
			  msgptr[0] = (c->msgptr)[12];
			  msgptr[1] = in;
			  msgptr[2] = (c->msgptr)[13];
			  dkapp_log_msg(c->a, DK_LOG_LEVEL_PROGRESS, msgptr, 3);
			}
		        if(!run_for_filenames(c, in, ofbuffer)) {
			  back = 0;
			}
		      }
		    } else {			
		      back = 0;
		      /* no suffix in file name, already tested in is_png() */
		    }
		  } else {			
		    /* File name too long, should not happen */
		    back = 0;
		    if((c->a) && (c->msgptr)) {
		      char *msgptr[3];
		      msgptr[0] = (c->msgptr)[25];
		      msgptr[1] = in;
		      msgptr[2] = (c->msgptr)[26];
		      dkapp_log_msg(c->a, DK_LOG_LEVEL_ERROR, msgptr, 3);
		    }
		  }
		}
	      }
	    }
	  } else {
	    back = 0;
	    /* no short filename for entry */
	    if((c->a) && (c->msgptr)) {
	      dkapp_log_msg(c->a, DK_LOG_LEVEL_ERROR, &((c->msgptr)[24]), 1);
	    }
	  }
	} else {
	  back = 0;
	  /* no filename for entry */
	  if((c->a) && (c->msgptr)) {
	    dkapp_log_msg(c->a, DK_LOG_LEVEL_ERROR, &((c->msgptr)[24]), 1);
	  }
	}
      }
      dkdir_close(dirptr);
    } else {		
      if(c->a) { dkapp_err_traverse_dir(c->a, c->inputfilename); }
    }
    dk_delete(ofbuffer);
  } else {		
    if(c->a) { dkapp_err_memory(c->a, 1, mpl); }
  }
  return back;
}



static int
run_for_output_name DK_P3(Png2PdfCmd *,c,char *,i,char *,o)
{
  int back = 0;
  
  if(dksf_must_expand_filename(i)) {
    dk_fne_t *ifne; char *in;		
    ifne = dkfne_open(i, 1, 0);
    if(ifne) {		
      if(c->a) {	
        in = dkapp_fne_one(c->a, ifne, i);
	if(in) {	
	  back = run_for_filenames(c, in, o);
	  dk_delete(in);
	} else {	
	}
      } else {		
        if(dkfne_next(ifne)) {	
	  in = dkfne_get_fullname(ifne);
	  if(in) {
	    back = run_for_filenames(c, in, o);
	  }
	  if(dkfne_next(ifne)) {	
	    /* ERROR: Pattern not unique */
	  }
	} else {	
	  /* ERROR: No such file name */
	}
      }
      dkfne_close(ifne);
    } else {		
      if(c->a) { dkapp_err_memory(c->a, sizeof(dk_fne_t), 1); }
    }
  } else {	
    back = run_for_filenames(c, i, o);
  } 
  return back;
}


static int
run_normally DK_P1(Png2PdfCmd *,c)
{
  int back = 0;
  
  if(c->inputfilename) {	
    if(c->outputfilename) {	
      if(dksf_must_expand_filename(c->outputfilename)) {
        dk_fne_t *ofne; char *on;	
	ofne = dkfne_open(c->outputfilename, 1, 0);
	if(ofne) {		
	  if(c->a) {		
	    on = dkapp_fne_one(c->a, ofne, c->outputfilename);
	    if(on) {		
	      back = run_for_output_name(c, c->inputfilename, on);
	      dk_delete(on);
	    } else {		
	    }
	  } else {		
	    if(dkfne_next(ofne)) {
	      on = dkfne_get_fullname(ofne);
	      if(on) {
	        back = run_for_output_name(c, c->inputfilename, on);
	      }
	    } else {		
	      /* ERROR: No such file */
	    }
	  }
	  dkfne_close(ofne);
	} else {		
	  if(c->a) { dkapp_err_memory(c->a, sizeof(dk_fne_t), 1); }
	}
      } else {	
        back = run_for_output_name(c, c->inputfilename, c->outputfilename);
      }
    } else {			
      if(dksf_must_expand_filename(c->inputfilename)) {
        
        back = run_for_output_name(c, c->inputfilename, NULL);
      } else {	
        if(isdir(c->inputfilename)) {
	  
	  back = run_for_directory(c);
	} else {
	  
	  back = run_for_output_name(c, c->inputfilename, NULL);
	}
      }
    }
  } else {	
    c->inf = stdin;
    c->of = stdout;
    dksf_set_file_binary(stdin);
    dksf_set_file_binary(stdout);
    back = png2pdf_for_files(c);
    c->inf = NULL; c->of = NULL;
  } 
  return back;
}


#ifndef VERSNUMB
#define VERSNUMB "1.0.12a"
#endif
static char versno[] = { VERSNUMB };



static char *help_text[] = {
"png2pdf [ <options> ]    [ <inputfile> [ <outputfile> ] ]",
"",
"Options:",
"-p PDF-level  PDF-level: 1.2, 1.3 or 1.4",
"-m r,g,b      default background color (used if there is no background chunk)",
"-s            always use default background color from -m option",
"-i            create image mask",
"-a            write transparency data",
"-b            fill background before rendering image",
"-f            file time check when running on directory",
"",
"Permanent options handling:",
"png2pdf -c <options>       configures permanent options",
"png2pdf -u                 removes all permanent options",
"png2pdf -C                 shows the permanent options",
"png2pdf -r <options> ...   temporarily overrides permanent options",
"",
"Help and version information:",
"png2pdf -h                 shows this help text",
"png2pdf -v                 shows version information",
"",
  NULL
};



static char *license_terms[] = {
"Redistribution and use in source and binary forms, with or without",
"modification, are permitted provided that the following conditions are met:",
"* Redistributions of source code must retain the above copyright notice, this",
"  list of conditions and the following disclaimer.",
"* Redistributions in binary form must reproduce the above copyright notice,",
"  this list of conditions and the following disclaimer in the documentation",
"  and/or other materials provided with the distribution.",
"* Neither the name of the Dirk Krause nor the names of other contributors may",
"  be used to endorse or promote products derived from this software without",
"  specific prior written permission.",
"THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"",
"AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE",
"IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE",
"ARE DISCLAIMED.",
"IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY",
"DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES",
"(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;",
"LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND",
"ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT",
"(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS",
"SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.",
NULL
};



static int
run DK_P3(dk_app_t *,a,int,xargc,char **,xargv)
{
  int back = 0;
  Png2PdfCmd	c;
  
  if(png2pdf_initialize_cmd(&c, a)) {
    back = 1;
    png2pdf_process_args(&c, xargc, xargv);
    if(c.error_code) { c.cmd |= PNG2PDF_CMD_HELP; back = 0; }
    if(c.cmd) {
      if(c.cmd & (PNG2PDF_CMD_HELP | PNG2PDF_CMD_VERSION)) {
        char **ptr;
	fputc('\n', stdout);
	fputs("png2pdf, version ", stdout);
	fputs(versno, stdout);
	fputc('\n', stdout);
	fputs("Copyright (C) 2003-2005 Dipl.-Ing. D. Krause\n",
	stdout);
	fputs("http://png2pdf.sourceforge.net\n",
	stdout);
	ptr = license_terms;
	while(*ptr) {
	  fputs(*(ptr++), stdout);
	  fputc('\n', stdout);
	}
	fputs("\nLibraries used:\n\n",
	stdout);
	fputs("libpng\tthe official PNG reference library\n",
	stdout);
	fputs("zlib\tgeneral compression library\n",
	stdout);
	fputs("dklibs\tportability layer and general purpose library\n",
	stdout);
	fputc('\n', stdout);
	if(c.cmd & PNG2PDF_CMD_HELP) {
	  /* ##### print help */
	  dkapp_help(a, "png2pdf.txt", help_text);
	}
      } else {
        if(c.cmd & PNG2PDF_CMD_UNCONFIGURE) {
	  png2pdf_reset_cmd(&c);
	  dkapp_unconfigure(a);
	}
	if(c.cmd & PNG2PDF_CMD_CONFIGURE) {
	  png2pdf_save_configuration(&c);
	}
	png2pdf_print_configuration(&c);
      }
    } else {		
      back = run_normally(&c);
    }
    png2pdf_uninitialize_cmd(&c);
  }
  
  return back;
}

#ifndef SYSCONFDIR
#define SYSCONFDIR "/etc"
#endif
static char sysconfdir[]  = { SYSCONFDIR };
static char packagename[] = { "png2pdf" };

#if DK_HAVE_PROTOTYPES
int main(int argc, char *argv[])
#else
int main(argc,argv) int argc; char *argv[];
#endif
{
  int exval = 0, rs = 0, rf = 0;
  int xargc; char **xargv;
  dk_app_t *app;
  
#line 552 "png2pdfm.ctr"

  
  silence_check(argc,argv,&rs,&rf); 
  if(!rs) { rs = dkapp_silence_check(argc,argv); }
  app = dkapp_open_ext1(argc, argv, packagename, sysconfdir, rs, rf);
  if(app) {
    xargc = dkapp_get_argc(app);
    xargv = dkapp_get_argv(app);
    exval = run(app, xargc, xargv);
    dkapp_close(app); app = NULL;
  } else {
    if(!rs) {
      fputs("ERROR: Not enough memory!\n", stderr);
      fflush(stderr);
    }
  }
  exval = (exval ? 0 : 1);
  
  
#line 570 "png2pdfm.ctr"

  exit(exval); return exval;
}

#ifndef LINT
static char sccs_id[] = {
"@(#)png2pdfm.ctr 1.24 07/18/06 (krause)\tPNG to PDF converter"
};
#endif

