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



#include <dk.h>

#ifndef SIZEOF_SIZE_T
/** Fallback define. */
#define SIZEOF_SIZE_T 4
#endif

#if SIZEOF_SIZE_T == 8
/** Maximum size_t value. */
#define DK_MAX_SIZE_T 0xFFFFFFFFFFFFFFFFULL
#else
#if SIZEOF_SIZE_T == 4
/** Maximum size_t value. */
#define DK_MAX_SIZE_T 0xFFFFFFFFUL
#else
/** Maximum size_t value. */
#define DK_MAX_SIZE_T 0xFFFFU
#endif
#endif

#include <dkapp.h>
#include <dklic.h>
#include <dkbf.h>
#include <dkstr.h>
#include <dklogc.h>
#include <dktypes.h>

#if DK_HAVE_STDIO_H
#include <stdio.h>
#endif
#if DK_HAVE_STDLIB_H
#include <stdlib.h>
#endif
#if DK_HAVE_PWD_H
#include <pwd.h>
#endif

#include "dktools-version.h"



/**	Application.
*/
dk_app_t *app = NULL;



/**	Buffer for UID range.
*/
static char uid_range[32];



/**	Buffer for output.
*/
static char write_buffer[32];



/**	Preference key to retrieve UID range.
*/
static char key_range[] = { "/uid/range" };



/**	Message texts, filled using the string finder.
*/
static char *msg_str[11];



/**	String finder table.
*/
static dk_string_finder_t msg_find[] = {
  { "/uid/e/000", &(msg_str[0]), "Range \"" },
  { "/uid/e/001", &(msg_str[1]), "\"-\"" },
  { "/uid/e/002", &(msg_str[2]), "\" too large!" },
  { "/uid/e/003", &(msg_str[3]), "Range \"" },
  { "/uid/e/004", &(msg_str[4]), "\"-\"" },
  { "/uid/e/005", &(msg_str[5]), "\" not valid!" },
  { "/uid/e/006", &(msg_str[6]), "Range needed!" },
  { "/uid/e/007", &(msg_str[7]), "No free UID available in range!" },
  { "/uid/e/008", &(msg_str[8]), "No getpwent() function available!" },
  { "/uid/cc", &(msg_str[9]), "Current configuration:" },
  { "/uid/cc-range", &(msg_str[10]), "UID range:" },
  { NULL, NULL, NULL }
};



/**	Long options.
*/
static char *long_option_keywords[] = {
  "v$ersion", "h$elp", "c$onfigure", "u$nconfigure", "sh$ow-configuration",
  NULL
};



/**	License terms.
*/
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
};



/**	Print version number.
*/
static void print_version DK_P0()
{
  char **ptr;
  printf("\n");
  printf(
    "uid (part of the dktools collection, version %s)\n",
    VERSNUMB
  );
  printf("Copyright (C) 2001-2010 Dipl.-Ing. D. Krause\n");
  printf("http://dktools.sourceforge.net/\n\n");
  ptr = license_terms;
  while(*ptr) {
    printf("%s\n", *(ptr++));
  }
  printf("\nLibraries used:\n\n");
  ptr = dklic_get();
  while(*ptr) {
    printf("%s\n", *(ptr++));
  }
  printf("\n");
}



/**	Help text.
*/
static char *help_text[] = {
  "",
  "uid - find free user id",
  "=======================",
  "",
  "Usage:",
  "",
  "uid <min> <max>",
  "",
  "min: minimum user id",
  "max: maximum user id",
  "",
  "Example:",
  "",
  "uid 3000 4000",
  "",
  NULL
};



/**	Print help text.
*/
static void print_help DK_P0()
{
  dkapp_help(app, "uid.txt", help_text);
}



/**	Run the program.
	Check whether to run normally or to print help text or version 
	information.
	@param	argc	Number of command line arguments.
	@param	argv	Command line arguments array.
	@return	1 on success, 0 on errors.
*/
static
int
run_main DK_P2(int, argc, char **,argv)
{
  int back = 0;
  char *r, *r1, *r2;
  unsigned long min, max, diff, x;
  size_t num, xnum;
  dk_bitfield_t *bf;
  struct passwd *pwent;
  int  cc, i, help_wanted, version_wanted, do_configure, un_configure;
  int  do_showconf;
  char *cptr, **lfdptr;
  char *logmsg[6];

  r = r1 = r2 = NULL; help_wanted = version_wanted = 0;
  do_configure = do_showconf = un_configure = 0;
  if(dkapp_get_pref(app, key_range, uid_range, sizeof(uid_range), 0)) {
    r = uid_range;
  }
  /*
  if(argc > 1) {
    r = r1 = argv[1];
  }
  if(argc > 2) {
    r2 = argv[2];
  }
  */
  i = 1; lfdptr = argv; lfdptr++;
  while(i < argc) {
    cptr = *lfdptr;
    if(*cptr == '-') {
      cptr++;
      switch(*cptr) {
        case '-': {
	  cptr++;
	  switch(dkstr_array_abbr(long_option_keywords, cptr, '$', 0)) {
	    case 0: version_wanted = 1; break;
	    case 1: help_wanted = 1; break;
	    case 2: do_configure = 1; break;
	    case 3: un_configure = 1; break;
	    case 4: do_showconf = 1; break;
	  }
	} break;
	case 'v': {
	  version_wanted = 1;
	} break;
	case 'h': {
	  help_wanted = 1;
	} break;
	case 'c': {
	  do_configure = 1;
	} break;
	case 'u': {
	  un_configure = 1;
	} break;
	case 'C': {
	  do_showconf = 1;
	} break;
      }
    } else {
      if(r1) {
        if(!r2) {
	  r2 = cptr;
	}
      } else {
        r1 = cptr;
      }
    }
    i++; lfdptr++;
  }
  if(help_wanted || version_wanted) {
    back = 1;
    if(version_wanted) {
      print_version();
    }
    if(help_wanted) {
      print_help();
    }
  } else {
    if(un_configure) {
      dkapp_unconfigure(app);
    } else {
      if(do_configure || do_showconf) {
        /* normal run */
        if(!r1) { r1 = r; }
        if(!r2) {
          if(r1) {
            r2 = dkstr_chr(r1, '-');
            if(r2) { *(r2++) = (char)0; }
          }
        }
        if(r1 && r2) {
          if((sscanf(r1, "%lu", &min) == 1) && (sscanf(r2, "%lu", &max) == 1)) {
            if(max < min) {
              diff = min;
	      min = max;
	      max = diff;
            }
	    sprintf(write_buffer, "%lu-%lu", min, max);
	    if(do_configure) {
              if(dkapp_set_pref(app, key_range, write_buffer)) {
	        back = 1;
	      }
	    }
	    fputs(msg_str[9], stdout);
	    fputc('\n', stdout);
	    fputs(msg_str[10], stdout);
	    fputc(' ', stdout);
	    fputs(write_buffer, stdout);
	    fputc('\n', stdout);
          } else {
            /* ERROR: Invalid range */
            logmsg[0] = msg_str[3];
            logmsg[1] = r1;
            logmsg[2] = msg_str[4];
            logmsg[3] = r2;
            logmsg[4] = msg_str[5];
            dkapp_log_msg(app, DK_LOG_LEVEL_ERROR, logmsg, 5);
          }
        } else {
          /* ERROR: Range needed */
          logmsg[0] = msg_str[6];
          dkapp_log_msg(app, DK_LOG_LEVEL_ERROR, logmsg, 1);
        }
      } else {
        /* normal run */
        if(!r1) { r1 = r; }
        if(!r2) {
          if(r1) {
            r2 = dkstr_chr(r1, '-');
            if(r2) { *(r2++) = (char)0; }
          }
        }
        if(r1 && r2) {
          if((sscanf(r1, "%lu", &min) == 1) && (sscanf(r2, "%lu", &max) == 1)) {
            if(max < min) {
              diff = min;
	      min = max;
	      max = diff;
            }
            diff = max - min + 1;
            if(diff > (unsigned long)DK_MAX_SIZE_T) {
              /* ERROR: Range too large */
	      logmsg[0] = msg_str[0];
	      logmsg[1] = r1;
	      logmsg[2] = msg_str[1];
	      logmsg[3] = r2;
	      logmsg[4] = msg_str[2];
              dkapp_log_msg(app, DK_LOG_LEVEL_ERROR, logmsg, 5);
            } else {
              num = (size_t)diff;
	      bf = dkbf_open(num);
	      if(bf) {
#if DK_HAVE_SETPWENT
                setpwent();
#endif
                while((pwent = getpwent()) != NULL) {
	          x = (unsigned long)(pwent->pw_uid);
	          if((x >= min) && (x <= max)) {
	            diff = x - min;
	            dkbf_set(bf, (size_t)diff, 1);
	          }
	        }
#if DK_HAVE_ENDPWENT
                endpwent();
#endif
                cc = 1; xnum = 0;
	        while(cc) {
		  if(xnum >= num) {
		    cc = 0;
		  } else {
		    
		    if(!dkbf_get(bf, xnum)) {
		      x = (unsigned long)xnum;
		      printf("%lu\n", (min + x));
		      cc = 0;
		      back = 1;
		    } else {
		      xnum++;
		    }
		  }
	        }
	        dkbf_close(bf); bf = NULL;
	        if(!back) {
	          /* ERROR: No free UID in range */
	          logmsg[0] = msg_str[7];
	          dkapp_log_msg(app, DK_LOG_LEVEL_ERROR, logmsg, 1);
	        }
	      } else {
	        dkapp_err_memory(app, sizeof(dk_bitfield_t), 1);
	      }
            }
          } else {
            /* ERROR: Invalid range */
            logmsg[0] = msg_str[3];
            logmsg[1] = r1;
            logmsg[2] = msg_str[4];
            logmsg[3] = r2;
            logmsg[4] = msg_str[5];
            dkapp_log_msg(app, DK_LOG_LEVEL_ERROR, logmsg, 5);
          }
        } else {
          /* ERROR: Range needed */
          logmsg[0] = msg_str[6];
          dkapp_log_msg(app, DK_LOG_LEVEL_ERROR, logmsg, 1);
        }
      }
    }
  }
  return back;
}



/**	The main() function of the uid program.
	@param	argc	Number of command line arguments.
	@param	argv	Command line arguments array.
	@return	1 on success, 0 on 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 xargc; char **xargv;
#if !DK_HAVE_GETPWENT
  char *logmsg[2];
#endif
  
#line 469 "uid.ctr"

  app = dkapp_open(argc, argv);
  if(app) {
    dkapp_find_multi(app, msg_find, "uid");
    xargc = dkapp_get_argc(app);
    xargv = dkapp_get_argv(app);
#if DK_HAVE_GETPWENT
    exval = run_main(xargc, xargv);
#else
    logmsg[0] = msg_str[8];
    dkapp_log_msg(app, DK_LOG_LEVEL_ERROR, logmsg, 1);
#endif
    dkapp_close(app); app = NULL;
  } else {
    if(!dkapp_silence_check(argc,argv)) {
      fprintf(stderr, "ERROR: Not enough memory!\n");
      fflush(stdout);
    }
  }
  
#line 488 "uid.ctr"

  exval = (exval ? 0 : 1);
  exit(exval); return exval;
}


