/*
 * This code is part of Screws project.
 * Copylefted by pancake@phreaker.net at 2003
 */

#include "Args.h"
#include "Config.h"

struct Args Args;

/* A strdup+free substitute */
int
freedup(dst,src)
	char **dst,*src;
{
#if HAXOR
	(!*dst)?:free(*dst);
#else
	if (*dst)free(*dst);
#endif
	*dst =  strdup(src);
	return  (int)dst;
}

/* Helpy stuff message */
int
showUsage(ret)
	int ret;
{
	printf( "Usage: %s [options]\n"
		" -c [cfgfile]   ::   Set configfile to read.\n"
		" -p [prgname]   ::   Set program name.\n"
		" -v #           ::   Verbose level.\n"
      " -l             ::   List all ConfigFile directives.\n"
		" -s             ::   Be strict.\n"
		" -d             ::   Run as daemon, aka setsid.\n"
		" -o             ::   Show the static options compiled.\n"
		" -h             ::   Show this helpy stuff.\n",Args.progname);
	exit(ret);
}

int
showOptions()
{
	printf ("Screws static options:\n"
		"  PREFIX     : %s\n"
		"  EXEC       : %s\n"
		"  MODULEPATH : %s\n"
		"  CFGFILE    : %s\n"
		"  VERSION    : %s\n"
		"  DEBUG      : %d\n"
		"  POLL       : %d\n"
		"  IPV6       : %d\n"
		"  SSL        : %d\n"
		"  MODULES    : %d\n",
		PREFIX,EXEC,MODULE_PATH,CFGFILE,VERSION,DEBUG,POLL,IPV6,USESSL,DLOPEN);
	return ERROR_NULL;
}

int
showDirectives()
{
	int i;
	printf("# screws - default configuration sketch\n");
	for(i=0;i<K_LASTONE;i++)
	{
		printf("# %s\n",conf_keys[i]);
	}
	return ERROR_NULL;
}

/* Set default options */
void
resetArgs(progname)
	char *progname;
{
	Args.cfg     =strdup(CFGFILE);
	Args.progname=strdup(progname);
	Args.daemon  =false;
	Args.setname =false;
	Args.strict  =false;
	Args.v       =-1;
}

/* Check if arg have one arg near it */
int
haveOneArg(i,argc,opt)
	int i,argc;
	char opt;
{
	if (i+1==argc)
	{	printf("++ Option '-%c' needs one argument\n",opt);
		return 0;
	} else  return 1;
}

/* Analize args */
int
getArgs(argc,argv)
	int argc;
	char *argv[];
{
	register int i=0;
	
	resetArgs(argv[0]);
	for(i=1; i<argc; i++)
	{
	    if ( argv[i][0]=='-' && strlen(argv[i])==2 )
	    {
	     switch(argv[i][1])
		{
		case 'c':
			if ( haveOneArg(i,argc,argv[i][1]) )
				freedup(&Args.cfg,argv[++i]);
			break;
		case 'v':
			if ( haveOneArg(i,argc,argv[i][1]) )
				Args.v = get_int(argv[++i],0,true,0);
			break;
		case 'p':
			if ( haveOneArg(i,argc,argv[i][1]) )
				freedup(&Args.progname,argv[++i]);
			Args.setname=true;
			break;
		case 's':
			Args.strict=true;
			break;
		case 'd':
			Args.daemon=true;
			break;
		case 'l':
			return showDirectives();
			break;
		case 'o':
			return showOptions();
			break;
		case 'h':
			return showUsage(0);
			break;
		default:
			printf("++ Option '-%c' not understood.\n",argv[i][1]);
			break;
		}
	    } else {
	       printf("++ Invalid argument '%s'\n", argv[i]);
	       return showUsage(1);
	    }
	}
	return ERROR_VOID;
}


