/*
jlayout - A Java code generator for GUI layout
Copyright (c) 2007-2010, 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
  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.
*/


/**	@file	jlmain.c	The jlmain module of the jlayout program.
*/



#include "jl.h"
#include "dktools-version.h"




#line 50 "jlmain.ctr"





/**	String table containing localized messages.
*/
static char sttname[] = { "jlayout" };



/**	Message to print if the string table cant be read.
*/
static char str_failed_to_read_string_table[] = {
"Failed to read messages from stringtable!"
};



/**	Long options.
*/
static char *long_options[] = {
  "version",		/*	0 */
  "help",		/*	1 */
  "configure",		/*	2 */
  "unconfigure",	/*	3 */
  "reset",		/*	4 */
  "show-configuration",	/*	5 */
  "silently",		/*	6 */
  NULL
};



/**	Version and license terms.
*/
static char *version_text[] = {
"",
"jlayout, version " VERSNUMB,
"Copyright (C) 2007-2010 Dipl.-Ing. D. Krause",
"http://dktools.sourceforge.net/jlayout.html",
"",
"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
};



/**	Default help text if help text file is not found.
*/
static char *help_text[] = {
"Usage:",
"------",
"",
"jlayout <layout-file-name> [<java-file-name>]",
"",
"The program processes a layout file (suffix *.jl) and modifies",
"a Java source file (suffix *.java).",
"If no Java source file name is specified, jlayout runs as a filter.",
NULL
};



/**	File name for help text file.
*/
static char help_file_name[] = { "jlayout.txt" };



/**	Check whether or not to run silently.
	@param	argc	Number of command line arguments.
	@param	argv	Command line arguments array.
	@param	rs	Pointer to result variable (silently).
	@param	rf	Pointer to result variable (filter).
*/
static
void
silence_check DK_P4(int,argc, char **,argv, int *,rs, int *,rf)
{
  int i; char *ptr, **lfdptr;
  int myrf = 2, myrs = 0;
  lfdptr = argv; lfdptr++; i = 1;
  
  while(i < argc) {
    ptr = *lfdptr;
    if(*ptr == '-') {
      ptr++;
      if(*ptr == '-') {
        ptr++;
	switch(dkstr_array_abbr(long_options, ptr, '$', 0)) {
	  case 6: myrs = 1; break;
	}
      } else {
        switch(*ptr) {
	  case 's': {
	    myrs = 1;
	  } break;
	}
      }
    } else {
      myrf--;
      if(myrf < 0) myrf = 0;
    }
    lfdptr++; i++;
  }
  if(rs) { *rs = myrs; }
  if(rf) { *rf = myrf; }
  
}



/**	Reset all configurable options to default values.
	@param	j	Jlayout job.
*/
static
void
reset_all_options_to_defaults DK_P1(JLJ *,j)
{
  /* ## no options to reset ## */
}



/**	Interpretation of command line arguments.
	@param	j	Jlayout job.
	@return 1 on success, 0 on error.
*/
static
int
check_arguments DK_P1(JLJ *,j)
{
  int back = 1;
  int i; char *ptr, **lfdptr;
  
  lfdptr = j->av; lfdptr++; i = 1;
  while(i < j->ac) {
    ptr = *lfdptr;
    if(*ptr == '-') {		
      ptr++;
      switch(*ptr) {
        case 'h': {
	  j->cmd |= RUN_CMD_HELP;
	} break;
	case 'v': {
	  j->cmd |= RUN_CMD_VERSION;
	} break;
	case 'c': {
	  j->cmd |= RUN_CMD_CONFIGURE;
	} break;
	case 'u': {
	  j->cmd |= RUN_CMD_UNCONFIGURE;
	} break;
        case 'C': {
	  j->cmd |= RUN_CMD_SHOW_CONFIG;
	} break;
	case 'r': {
	  reset_all_options_to_defaults(j);
	} break;
	case '-': {
	  ptr++;
	  switch(dkstr_array_abbr(long_options, ptr, '$', 0)) {
	    case 0: {	/* version */
	      j->cmd |= RUN_CMD_VERSION;
	    } break;
	    case 1: {	/* help */
	      j->cmd |= RUN_CMD_HELP;
	    } break;
	    case 2: {	/* configure */
	      j->cmd |= RUN_CMD_CONFIGURE;
	    } break;
	    case 3: {	/* unconfigure */
	      j->cmd |= RUN_CMD_UNCONFIGURE;
	    } break;
	    case 4: {	/* reset */
	      reset_all_options_to_defaults(j);
	    } break;
	    case 5: {	/* show configuration */
	      j->cmd |= RUN_CMD_SHOW_CONFIG;
	    } break;
	  }
	} break;
      }
    } else {			
      if(j->ifnameorig) {
        if(j->ofnameorig) {	
	  /* ERROR: Too many file names */
	  jlmsg_log1(j, DK_LOG_LEVEL_ERROR, 0);
	  back = 0;
	} else {
	  j->ofnameorig = ptr;
	}
      } else {
        j->ifnameorig = ptr;
      }
    }
    i++; lfdptr++;
  }
  if(!(j->ifnameorig)) {
    if(j->cmd == RUN_CMD_RUN) {
      back = 0;
      jlmsg_log1(j, DK_LOG_LEVEL_ERROR, 1);
    }
  }
  if(!back) { j->exval = 1; }
  
  return back;
}



/**	Print version number.
	@param	j	Jlayout job.
*/
static
void
print_version DK_P1(JLJ *,j)
{
  char **xptr;
  
  xptr = version_text;
  while(*xptr) {
    fputs(*(xptr++), stdout); fputc('\n', stdout);
  }
  fputc('\n', stdout);
  xptr = dklic_get();
  fputs("Libraries used:\n\n", stdout);
  while(*xptr) {
    fputs(*(xptr++), stdout); fputc('\n', stdout);
  }
  fputc('\n', stdout);
}



/**	Print help text.
	@param	j	Jlayout job.
*/
static
void
print_help DK_P1(JLJ *,j)
{
  dkapp_help(j->a, help_file_name, help_text);
}



/**	Save the current settings as default
	configuration.
	@param	j	Jlayout job.
*/
static
void
setup_configuration DK_P1(JLJ *,j)
{
  /* ## nothing to configure as preferences ## */
}



/**	Print the current configuration.
	@param	j	Jlayout job.
*/
static
void
print_configuration DK_P1(JLJ *,j)
{
  /* ## no preferences to print ## */
}



/**	Remove permanent settings.
	@param	j	Jlayout job.
*/
static
void
unset_configuration DK_P1(JLJ *,j)
{
  if(j->a) {
    dkapp_unconfigure(j->a);
  }
}



/**	Inspect command line options and run action
	whatever necessary, either do a conversion or
	show help text.
	@param	j	Jlayout job.
*/
static
void
run DK_P1(JLJ *,j)
{
  int checkres = 0;
  
  j->ac = dkapp_get_argc(j->a);
  j->av = dkapp_get_argv(j->a);
  jlconf_read(j);
  checkres = check_arguments(j);
  if(j->cmd) {
    /*
    	Anything other than normal program run
    */
    if((j->cmd) & (RUN_CMD_VERSION | RUN_CMD_HELP)) {
        print_version(j);
	if((j->cmd) & RUN_CMD_HELP) {
	  print_help(j);
	}
    } else {
        if((j->cmd) & (RUN_CMD_VERSION | RUN_CMD_HELP)) {
	  if((j->cmd) & RUN_CMD_CONFIGURE) {
	    setup_configuration(j);
	  }
	  print_configuration(j);
	} else {
	  if((j->cmd) & RUN_CMD_UNCONFIGURE) {
	    unset_configuration(j);
	  }
	}
    }
  } else {
    /*
    	Normal program run
    */
    
    if(checkres) {
      int can_run = 1;
      dk_fne_t *fneif = NULL, *fneof = NULL;
      /*
      	If file names contain wildcards, expand the names
      */
      if(j->ifnameorig) {
        if(dksf_must_expand_filename(j->ifnameorig)) {
	  fneif = dkfne_open(j->ifnameorig, 1, 0);
	  if(fneif) {
	    j->ifname = dkfne_get_one(fneif);
	    if(!(j->ifname)) {
	      can_run = 0;
	      /* ERROR: ... must match exactly one file name */
	      jlmsg_log1(j, DK_LOG_LEVEL_ERROR, 18);
	    }
	  } else {
	    can_run = 0;
	    /* ERROR: Failed to open fne */
	    jlmsg_log1(j, DK_LOG_LEVEL_ERROR, 19);
	  }
	} else {
	  j->ifname = j->ifnameorig;
	}
      } else {
        can_run = 0;
      }
      if(j->ofnameorig) {
        if(dksf_must_expand_filename(j->ofnameorig)) {
	  fneof = dkfne_open(j->ofnameorig, 1, 0);
	  if(fneof) {
	    j->ofname = dkfne_get_one(fneof);
	    if(!(j->ofname)) {
	      can_run = 0;
	      /* ERROR: ... must match exactly one file name */
	      jlmsg_log1(j, DK_LOG_LEVEL_ERROR, 20);
	    }
	  } else {
	    can_run = 0;
	    /* ERROR: Failed to open fne */
	    jlmsg_log1(j, DK_LOG_LEVEL_ERROR, 19);
	  }
	} else {
	  j->ofname = j->ofnameorig;
	}
      }
      /*
      	Now really run
      */
      if(can_run) {
        if(jlread(j)) {
          if(jlcheck(j)) {
	    if(jsrc_setup(j)) {
              if(jsrc_read(j)) {
	        if(jsrc_write(j)) {
	          
	        } else {
	          
	          /* error messages issued by jsrc_write() */
	        }
	      } else {
	        
	        /* errors messages issued by jsrc_read() */
	      }
	    } else {
	      
	      /* error messages issued by jsrc_setup() */
	    }
	    jsrc_cleanup(j);
          } else {
            
	    /* errors messages issued by jlcheck() */
          }
        } else {
          
          /* errors messages issued by jlread() */
        }
	jlcleanup(j);
      } else {
        j->exval = 1;
      }
      /*
      	Clean up file name expanders if necessary
      */
      if(fneof) {
        dkfne_close(fneof); fneof = NULL; j->ofname = NULL;
      }
      if(fneif) {
        dkfne_close(fneif); fneif = NULL; j->ifname = NULL;
      }
    } else {
      print_version(j);
      print_help(j);
    }
  }
  
  
}



/**	Input line buffer.
*/
static char ib[4096];



/**	The global jlayout job structure with default settings.
*/
static JLJ jlj = {
  NULL,			/*	a */
  0,			/*	ac */
  NULL,			/*	av */
  0,			/*	exval */
  NULL,			/*	ifnameorig */
  NULL,			/*	ofnameorig */
  NULL,			/*	ifname */
  NULL,			/*	ofname */
  NULL,			/*	msg */
  0,			/*	run_silently */
  0UL,			/*	errlineno */
  NULL,			/*	errfilename */
  RUN_CMD_RUN,		/*	cmd */
  NULL,			/*	l_st */
  NULL,			/*	l_it */
  0UL,			/*	ln_variables */
  0UL,			/*	ln_setup */
  0UL,			/*	ln_cleanup */
  0UL,			/*	ln_import */
  ib,			/*	input_buffer */
  sizeof(ib),		/*	sz_input_buffer */
  0U,			/*	f1 */
  NULL,			/*	o_st */
  NULL,			/*	o_it */
  NULL,			/*	g_st */
  NULL,			/*	g_it */
  NULL,			/*	b_st */
  NULL,			/*	b_it */
  NULL,			/*	uc_st */
  NULL,			/*	uc_it */
  NULL,			/*	o_main */
  NULL,			/*	o_cur */
  NULL,			/*	border (not specified) */
  FILL_NOT_SPECIFIED,	/*	fill */
  ANCHOR_NOT_SPECIFIED,	/*	anchor */
  0UL,			/*	max_obj_no */
  0UL,			/*	max_level */
  FOLD_MARKER_NETBEANS,	/*	foldmt */
  0x00,			/*	Use dklibsj */
  0x00			/*	freeze */
};



/**	The main() function of the jlayout program.
	@param	argc	Number of command line arguments.
	@param	argv	Command line arguments array.
	@return	0 on success, any other value indicates an error.
*/
#if DK_HAVE_PROTOTYPES
int
main(int argc, char *argv[])
#else
int
main(argc, argv) int argc; char *argv[];
#endif
{
  int rs = 0, rf = 0;
  dk_app_t *a = NULL;
  
#line 567 "jlmain.ctr"

  
  silence_check(argc, argv, &rs, &rf);
  if(rs) { jlj.run_silently |= 1; }
  if(rf) { jlj.run_silently |= 2; }
  a = dkapp_open_ext1(argc, argv, GROUPNAME, DK_SYSCONFDIR, rs, rf);
  if(a) {
    jlj.msg = dkapp_find_key_value(a, jlmsg_msg(), jlmsg_size(), sttname);
    if(jlj.msg) {
      jlj.a = a;
      run(&jlj);
      dk_delete(jlj.msg); jlj.msg = NULL;
    } else {
      char *msg[2];
      msg[0] = str_failed_to_read_string_table;
      dkapp_log_msg(a, DK_LOG_LEVEL_ERROR, msg, 1);
    }
    dkapp_close(a); a = NULL; jlj.a = NULL;
  } else {
    if(!rs) {
      fprintf(stderr, "Not enough memory (RAM/swap)!\n"); fflush(stderr);
    }
  }
  
  
#line 591 "jlmain.ctr"

  exit(jlj.exval); return jlj.exval;
}


