/*
Copyright (c) 2004-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	dksavepw.c	The dksavepw program.
*/



#include <dk.h>

#include <stdio.h>
#include <stdlib.h>
#if DK_HAVE_UNISTD_H
#include <unistd.h>
#endif
#if DK_HAVE_TERMIOS_H
#include <termios.h>
#endif
#if DK_HAVE_SYS_TERMIOS_H
#include <sys/termios.h>
#endif
#if DK_HAVE_SYS_TTOLD_H
#include <sys/ttold.h>
#endif
#if DK_HAVE_WINCON_H
#include <wincon.h>
#endif

#include <dksf.h>
#include <dklogc.h>
#include <dkmem.h>
#include <dkstr.h>
#include <dkapp.h>

#include "dktools-version.h"




#line 75 "dksavepw.ctr"





/*
  Name of the package including the program
*/
#ifndef PACKAGE_NAME
/**	Application group name. */
#define PACKAGE_NAME "dktools"
#endif



/**	Buffer length for password buffers.
*/
#define PASSWD_BUFFER_LENGTH 64



/**	Dksavepw job.
*/
typedef struct {
  dk_app_t	*app;		/**< Application. */
  char		*b1;		/**< Buffer 1. */
  char		*b2;		/**< Buffer 2. */
  char		**argv;		/**< Command line arguments array. */
  char		**msg;		/**< Localized messages. */
  char		*outfilename;	/**< output file name. */
  int		action;		/**< Action (ACTION_xxx). */
  size_t	bs;		/**< Size of \a b1 and \a b2. */
  int		argc;		/**< Number of command line arguments. */
  int		fl;		/**< Flags. */
} SavePasswdCmd;




/**	Flag: Force operation if failed to disable keyboard echo. */
#define FLAG_FORCE		1

/**	Flag: Write newline after password. */
#define FLAG_NEWLINE		2

/**	Flag: Have TTY. */
#define FLAG_TTY		4

/**	Flag: Have TERMIOS. */
#define FLAG_HAVE_TERMIOS	8



/**	Action: Show help text. */
#define ACTION_HELP		1

/**	Action: Show version and license. */
#define ACTION_VERSION		2

/**	Action: Configure (save preferences). */
#define ACTION_CONFIGURE	4

/**	Action: Unconfigure (forget preferences). */
#define ACTION_UNCONFIGURE	8

/**	Action: Show configuration. */
#define ACTION_SHOWCONF		16



/**	Application group name.
*/
static char packageName[] = { PACKAGE_NAME };



/**	System configuration directory.
*/
static char sysconfdir[] = { DK_SYSCONFDIR };



/**	Key value pairs for message names and default texts.
*/
static dk_key_value_t kv[] = {
  { "/m/00", "Warning: Failed to turn keyboard echo off!" },
  { "/m/01", "Do you want to continue?" },
  { "/m/02", "0 ... No, I don't." },
  { "/m/03", "1 ... Yes, I do." },
  { "/m/04", "Please enter the password: " },
  { "/m/05", "Please re-type the password: " },
  { "/m/06", "Password mismatch." },
  { "/m/07", "Password successfully saved to file." },
  { "/m/08", "Force operation if keyboard echo can not be turned off" },
  { "/m/09", "Write newline after password" },
  { "/m/10", "Current configuration:" },
  { "/m/11", "on" },
  { "/m/12", "off" },
  { "/m/13", "Missing output file name." }
};
/**	Number of entries in message key/value pairs.
*/
static size_t szkv = sizeof(kv)/sizeof(dk_key_value_t);



/**	Long options.
*/
static char *long_opt_kw[] = {
  "f$orce",
  "n$ewline",
  "v$ersion",
  "h$elp",
  "c$onfigure",
  "u$nconfigure",
  "s$how-configuration",
  "r$eset",
  NULL
};



/**	Preference key whether or not to force operation.
*/
static char pk_force[] = { "/force" };


/**	Preference key whether or not to store newline.
*/
static char pk_newline[] = { "/newline" };


/**	Preference value: "yes".
*/
static char pv_yes[] = { "yes" };


/**	Preference value: "no".
*/
static char pv_no[] = { "no" };


/**	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, filenames;
  char *ptr, **lfdptr;
  
  filenames = 0; lfdptr = argv;
  lfdptr++; i = 1;
  while(i < argc) {
    ptr = *lfdptr;
    if(*ptr == '-') {
      ptr++;
      if(*ptr == 's') {
        *rs = 1;
      }
    } else {
      filenames++;
    }
    i++; lfdptr++;
  }
  if(filenames < 1) {
    *rf = 1;
  }
  
}



/**	Set an option.
	@param	old	Previous options value.
	@param	fl	Bit to set or remove.
	@param	s	String containing a boolean value.
	@return	Modified options value.
*/
static
int
set_option DK_P3(int,old,int,fl,char *,s)
{
  int back;
  back = old;
  if(s) {
    if(*s) {
      if(dkstr_is_on(s)) {
        back |= fl;
      } else {
        back &= (~fl);
      }
    } else {
      back |= fl;
    }
  } else {
    back |= fl;
  }
  return back;
}



/**	Retrieve one setting from preferences, convert to int.
	@param	cmd	Dksavepw job.
	@param	pk	Preference key.
	@param	f	Flags value to add.
*/
static
void
one_option DK_P3(SavePasswdCmd *,cmd, char *,pk, int,f)
{
  char buffer[128], *ptr;
  if(dkapp_get_pref(cmd->app, pk, buffer, sizeof(buffer), 0)) {
    ptr = dkstr_start(buffer, NULL);
    if(ptr) {
      dkstr_chomp(ptr, NULL);
      if(dkstr_is_bool(ptr)) {
        if(dkstr_is_on(ptr)) {
	  cmd->fl |= f;
	} else {
	  cmd->fl &= (~(f));
	}
      }
    }
  }
}




/**	Read settings from preferences.
	@param	cmd	Dksavepw job.
*/
static
void
read_prefs DK_P1(SavePasswdCmd *,cmd)
{
  one_option(cmd, pk_force, FLAG_FORCE);
  one_option(cmd, pk_newline, FLAG_NEWLINE);
}



/**	Write one setting to preference.
	@param	cmd	Dksavepw job.
	@param	pk	Preference key.
	@param	f	Flag to write.
*/
static
void
write_one DK_P3(SavePasswdCmd *,cmd, char *,pk, int,f)
{
  if(f) {
    dkapp_set_pref(cmd->app, pk, pv_yes);
  } else {
    dkapp_set_pref(cmd->app, pk, pv_no);
  }
}



/**	Write settings to preferences.
	@param	cmd	Dksavepw job.
*/
static
void
write_prefs DK_P1(SavePasswdCmd *,cmd)
{
  write_one(cmd, pk_force, ((cmd->fl) & FLAG_FORCE));
  write_one(cmd, pk_newline, ((cmd->fl) & FLAG_NEWLINE));
}



/**	Ask user whether or not to proceed if keyboard echo not diabled.
	@param	cmd	Dksavepw job.
	@return	1=yes, 0=no.
*/
static
int
ask_for_unsecure_operation DK_P1(SavePasswdCmd *,cmd)
{
  int back = 0;
  int i;
  char buffer[32], *ptr;
  for(i = 0; i < 4; i++) {
    fputs((cmd->msg)[i], stdout); fputc('\n', stdout);
  }
  if(fgets(buffer, sizeof(buffer), stdin)) {
    ptr = dkstr_start(buffer, NULL);
    if(ptr) {
      dkstr_chomp(ptr, NULL);
      if(dkstr_is_on(ptr)) {
        back = 1;
      }
    }
  }
  return back;
}



/**	Get password and save it.
	@param	cmd	Dksavepw job.
	@param	ep	Keyboard echo disabler.
	@return	1 on success, 0 on error.
*/
static
int
get_pw_and_save DK_P2(SavePasswdCmd *,cmd, dk_echo_t *,ep)
{
  int back = 0;
  char *ptr1, *ptr2;
  
  if(dksf_echo_is_tty(ep)) {
    fputs((cmd->msg)[4], stdout);
  }
  if(fgets(cmd->b1, cmd->bs, stdin)) {
    
#if !DK_HAVE_TCGETATTR
#ifndef TCGETS
#if DK_HAVE_GETSTDHANDLE
    fputc('\n', stdout);
#endif
#endif
#endif
    if(dksf_echo_is_tty(ep)) {
      fputs((cmd->msg)[5], stdout);
    }
    if(fgets(cmd->b2, cmd->bs, stdin)) {
      
      ptr1 = dkstr_start(cmd->b1, NULL);
      ptr2 = dkstr_start(cmd->b2, NULL);
      if(ptr1 && ptr2) {
        dkstr_chomp(ptr1, NULL);
        dkstr_chomp(ptr2, NULL);
        if(strcmp(ptr1, ptr2) == 0) {
	  FILE *fipo;
          
	  fipo = dkapp_fopen(cmd->app, cmd->outfilename, "w");
	  if(fipo) {
	    char *x[3];
	    fputs(ptr1, fipo);
	    if((cmd->fl) & FLAG_NEWLINE) {
	      fputc('\n', fipo);
	    }
	    x[0] = (cmd->msg)[7];
	    fclose(fipo); fipo = NULL;
	    dkapp_log_msg(cmd->app, DK_LOG_LEVEL_INFO, x, 1);
	  } else {
	    dkapp_err_fopenw(cmd->app, cmd->outfilename);
	  }
        } else {
          char *x[3];
          x[0] = (cmd->msg)[6];
          dkapp_log_msg(cmd->app, DK_LOG_LEVEL_ERROR, x, 1);
        }
      }
    }
  } 
  return back;
}



/**	Get the password and save it, disable keyboard echo.
	@param	cmd	Dksavepw job.
	@return	1 on success, 0 on error.
*/
static
int
get_the_password DK_P1(SavePasswdCmd *,cmd)
{
  int back = 0;
  dk_echo_t echodata;
  if(dksf_echo_test_tty()) {
    if(dksf_echo_save(&echodata)) {
      if(dksf_echo_off(&echodata)) {
        back = get_pw_and_save(cmd,&echodata);
      } else {
        if(ask_for_unsecure_operation(cmd)) {
	  back = get_pw_and_save(cmd,&echodata);
	}
      }
      dksf_echo_restore(&echodata);
    } else {
      if(ask_for_unsecure_operation(cmd)) {
        back = get_pw_and_save(cmd,&echodata);
      }
    }
  } else {
    back = get_pw_and_save(cmd,&echodata);
  }
  return back;
}



/**	Reset job.
	@param	cmd	Dksavepw job.
*/
static
void
reset_cmd DK_P1(SavePasswdCmd *,cmd)
{
  cmd->fl &= (~(FLAG_FORCE | FLAG_NEWLINE));
}



/**	Text for version number and used libraries.
*/
static char *version_text[] = {
  "",
  "dksavepw (part of the dktools collection, version " VERSNUMB ")",
  "Copyright (C) 2004-2010 Dipl.-Ing. D. Krause",
  "http://dktools.sourceforge.net/",
  "",
"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
};



/**	Print version number.
	@param	cmd	Dksavepw job.
*/
static
void
print_version DK_P1(SavePasswdCmd *,cmd)
{
  char **ptr;
  ptr = version_text;
  while(*ptr) {
    fputs(*ptr, stdout); fputc('\n', stdout);
    ptr++;
  }
}



/**	Help text.
*/
static char *help_text[] = {
  "dksavepw - Enter a password and save to file",
  "--------------------------------------------",
  "-f     Force operation, even if the keyboard echo can not be turned off",
  "-n     Add newline after password",
  "",
  NULL
};



/**	Print help text.
	@param	cmd	Dksavepw job.
*/
static
void
print_help DK_P1(SavePasswdCmd *,cmd)
{
  dkapp_help(cmd->app, "dksavepw.txt", help_text);
}



/**	Multiple spaces.
*/
static char spaces[] = { "     " };



/**	Print on "on" or "off" value.
	@param	cmd	Dksavepw job.
	@param	f	Flag (on or off).
	@param	m	Screen space for value.
*/
static
void
print_on_off DK_P3(SavePasswdCmd *,cmd, int,f, size_t,m)
{
  size_t sz;
  if(f) {
    fputs((cmd->msg)[11], stdout);
    sz = strlen((cmd->msg)[11]);
  } else {
    fputs((cmd->msg)[12], stdout);
    sz = strlen((cmd->msg)[12]);
  }
  while(sz++ < m) fputc(' ', stdout);
}



/**	Show current configuration.
	@param	cmd	Dksavepw job.
*/
static
void
show_configuration DK_P1(SavePasswdCmd *,cmd)
{
  size_t sz, max;
  max = sz = strlen((cmd->msg)[11]);
  sz = strlen((cmd->msg)[12]);
  if(sz > max) max = sz;
  fputs((cmd->msg)[10], stdout); fputc('\n', stdout);
  fputs("-f", stdout);
  fputs(spaces, stdout);
  print_on_off(cmd, ((cmd->fl) & FLAG_FORCE), max);
  fputs(spaces, stdout);
  fputs((cmd->msg)[8], stdout); fputc('\n', stdout);
  fputs("-n", stdout);
  fputs(spaces, stdout);
  print_on_off(cmd, ((cmd->fl) & FLAG_NEWLINE), max);
  fputs(spaces, stdout);
  fputs((cmd->msg)[9], stdout); fputc('\n', stdout);
}



/**	Run.
	@param	cmd	Dksavepw job.
	@return	1 on success, 0 on error.
*/
static
int
run_main DK_P1(SavePasswdCmd *,cmd)
{
  int back = 0;
  int i; char *ptr, **lfdptr, *arg;
  
  lfdptr = cmd->argv; lfdptr++; i = 1;
  while(i < cmd->argc) {
    ptr = *lfdptr;
    if(*ptr == '-') {
      ptr++;
      if(*ptr == '-') {			
        ptr++;
        arg = strchr(ptr, '=');
	if(arg) {
	  *(arg++) = '\0';
	}
	switch(dkstr_array_abbr(long_opt_kw, ptr, '$', 0)) {
	  case 0: {	/* force */
	    cmd->fl = set_option(cmd->fl, FLAG_FORCE, arg);
	  } break;
	  case 1: {	/* newline */
	    cmd->fl = set_option(cmd->fl, FLAG_NEWLINE, arg);
	  } break;
	  case 2: {	/* version */
	    cmd->action |= ACTION_VERSION;
	  } break;
	  case 3: {	/* help */
	    cmd->action |= ACTION_HELP;
	  } break;
	  case 4: {	/* configure */
	    cmd->action |= ACTION_CONFIGURE;
	  } break;
	  case 5: {	/* unconfigure */
	    cmd->action |= ACTION_UNCONFIGURE;
	  } break;
	  case 6: {	/* show-configuration */
	    cmd->action |= ACTION_SHOWCONF;
	  } break;
	  case 7: {	/* reset */
	    reset_cmd(cmd);
	  } break;
	}
      } else {				
        switch(*ptr) {
	  case 'f' : {
	    ptr++;
	    cmd->fl = set_option(cmd->fl, FLAG_FORCE, ptr);
	  } break;
	  case 'n' : {
	    ptr++;
	    cmd->fl = set_option(cmd->fl, FLAG_NEWLINE, ptr);
	  } break;
	  case 'v' : {
	    cmd->action |= ACTION_VERSION;
	  } break;
	  case 'h' : {
	    cmd->action |= ACTION_HELP;
	  } break;
	  case 'c' : {
	    cmd->action |= ACTION_CONFIGURE;
	  } break;
	  case 'C' : {
	    cmd->action |= ACTION_SHOWCONF;
	  } break;
	  case 'u' : {
	    cmd->action |= ACTION_UNCONFIGURE;
	  } break;
	  case 'r' : {
	    reset_cmd(cmd);
	  } break;
	}
      }
    } else {
      if(!(cmd->outfilename)) {
        cmd->outfilename = ptr;
      } else {				
      }
    }
    lfdptr++; i++;
  }
  /*
  if(cmd->outfilename) {
    back = get_the_password(cmd);
  } else {				$? "! error: no output file name"
  }
  */
  if((cmd->action) & (ACTION_HELP | ACTION_VERSION)) {
    print_version(cmd);
    if((cmd->action) & ACTION_HELP) {
      print_help(cmd);
    }
    back = 1;
  } else {
    if((cmd->action)
       & (ACTION_CONFIGURE | ACTION_UNCONFIGURE | ACTION_SHOWCONF))
    {
      if((cmd->action) & ACTION_CONFIGURE) {
        write_prefs(cmd); back = 1;
      } else {
        if((cmd->action) & ACTION_UNCONFIGURE) {
	  dkapp_unconfigure(cmd->app);
	  reset_cmd(cmd);
	} else {
	}
      }
      show_configuration(cmd);
    } else {
      if(cmd->outfilename) {
        back = get_the_password(cmd);
      } else {
        char *x[3];
	x[0] = (cmd->msg)[13];
	dkapp_log_msg(cmd->app, DK_LOG_LEVEL_ERROR, x, 1);
      }
    }
  }
  
  return back;
}



/**	The main() function of the dksavepw 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 exval = 0;
  int rs = 0, rf = 0;
  SavePasswdCmd cmd;
  char buffer1[PASSWD_BUFFER_LENGTH];
  char buffer2[sizeof(buffer1)];
  
#line 763 "dksavepw.ctr"

  
  /* initialize cmd structure */
  DK_MEMRES(&cmd,sizeof(SavePasswdCmd)) ;
  cmd.b1 = buffer1; cmd.b2 = buffer2; cmd.bs = sizeof(buffer1);
  cmd.outfilename = NULL; cmd.action = 0;
  /* create application structure */
  silence_check(argc, argv, &rs, &rf);
  if(!rs) { rs = dkapp_silence_check(argc,argv); }
  cmd.app = dkapp_open_ext1(argc, argv, packageName, sysconfdir, rs, rf);
  if(cmd.app) {
    cmd.argc = dkapp_get_argc(cmd.app);
    cmd.argv = dkapp_get_argv(cmd.app);
    cmd.msg  = dkapp_find_key_value(cmd.app, kv, szkv, "dksavepw");
    if(cmd.msg) {
      char **cp;
      read_prefs(&cmd);
      exval = run_main(&cmd);
      cp = cmd.msg; dk_delete(cp); cmd.msg = NULL;
    } else {		
    }
    dkapp_close(cmd.app); cmd.app = NULL;
  } else {		
  }
  exval = (exval ? 0 : 1); 
  
#line 788 "dksavepw.ctr"

  exit(exval); return exval;
}


