/* 
   authentication client for podfuk-smb

   Copyright (C) Tim Potter 2000
   
   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2 of the License, or
   (at your option) any later version.
   
   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.
   
   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>

#include "podfuk-smb-auth.h"

/* Print usage information */

static void print_usage(char *prog)
{
	printf("Usage: %s [-arcClLf] [-U user%%pass] [-W workgroup] "
	       "[-S sharename]\n\n", prog);
	printf("Commands:\n");
	printf("\t-a\t\tadd user token\n");
	printf("\t-r\t\tremove user token\n");
	printf("\t-c\t\tclear user tokens\n");
	printf("\t-l\t\tlist user tokens\n");
	printf("\t-f\t\tfetch token (requires root)\n");
	printf("\t-C\t\tclear all tokens (requires root)\n");
	printf("\t-L\t\tlist all tokens (requires root)\n\n");
	printf("Arguments:\n");
	printf("\t-S sharename\tspecify sharename\n");
	printf("\t-U user%%pass\tspecify username and password\n");
	printf("\t-W workgroup\tspecify workgroup/domain\n\n");
	printf("Use a share name of //server to specify a "
	       "username/password for all shares on\n");
	printf("that server.  Use a share name of // to specify a "
	       "username/password for all\n");
	printf("servers.\n");
}

#ifdef __INSURE__

#include <dlfcn.h>

extern void pstring_sub(char *s,const char *pattern,const char *insert);

/*******************************************************************
This routine is a trick to immediately catch errors when debugging
with insure. A xterm with a gdb is popped up when insure catches
a error. It is Linux specific.
********************************************************************/
int _Insure_trap_error(int a1, int a2, int a3, int a4, int a5, int a6)
{
	static int (*fn)();
	int ret;
	char pidstr[10];
	pstring cmd = "/usr/X11R6/bin/xterm -T Panic -n Panic -e /bin/sh -c 'cat /tmp/ierrs.*.%d ; gdb /proc/%d/exe %d'";

	snprintf(pidstr, sizeof(pidstr) - 1, "%d", getpid());
	pstring_sub(cmd, "%d", pidstr);

	if (!fn) {
		static void *h;
		h = dlopen("/usr/local/parasoft/insure++lite/lib.linux2/libinsure.so", RTLD_LAZY);
		fn = dlsym(h, "_Insure_trap_error");
	}

	ret = fn(a1, a2, a3, a4, a5, a6);

	system(cmd);

	return ret;
}
#endif

/* 
 * Main function
 */

int main(int argc, char *argv[]) 
{
	int got_pass = False, got_user = False, got_workgroup = False,
		got_sharename = False;
	fstring sharename, workgroup, username, password;
	enum auth_cmd auth_cmd = -1;
	int opt;

	/* Parse options */

	if (argc == 1) {
		print_usage(argv[0]);
		return 1;
	}

	while((opt = getopt(argc, argv, "arcflLCU:W:S:")) != EOF) {
		switch(opt) {

			/* Misc commands */

		case 'a':
			auth_cmd = AUTH_ADD_TOKEN;
			break;

		case 'r':
			auth_cmd = AUTH_REMOVE_TOKEN;
			break;
			
		case 'c':
			auth_cmd = AUTH_CLEAR_TOKENS;
			break;
			
		case 'f':
			auth_cmd = AUTH_FETCH_TOKEN;
			break;

		case 'C':
			auth_cmd = AUTH_CLEAR_ALL_TOKENS;
			break;

		case 'l':
			auth_cmd = AUTH_LIST_TOKENS;
			break;

		case 'L':
			auth_cmd = AUTH_LIST_ALL_TOKENS;
			break;

			/* Specify sharename */

		case 'S':
			strncpy(sharename, optarg, sizeof(sharename) - 1);
			sharename[sizeof(workgroup) - 1] = '\0';
			got_sharename = True;
			break;

                        /* Specify username */     

		case 'U': {
			char *lp;
				
			strncpy(username, optarg, sizeof(username) - 1);
			username[sizeof(username) - 1] = '\0';
				
			if ((lp = strchr(username, '%'))) {
				*lp = 0;
				strncpy(password, lp + 1, 
					sizeof(password) - 1);
				password[sizeof(password) - 1] = '\0';
				got_pass = True;
				memset(strchr(optarg,'%') + 1,
				       'X', strlen(password));
			}
			
			got_user = True;
			break;
		}

			/* Specify workgroup/domain */

		case 'W':
			strncpy(workgroup, optarg, sizeof(workgroup) - 1);
			workgroup[sizeof(workgroup) - 1] = '\0';
			got_workgroup = True;
			break;

			/* Print help */

		case 'h':
			print_usage(argv[0]);
			return 1;		

			/* Unknown option */

		default:
			fprintf(stderr, "unknown option %c\n", (char)opt);
			return 1;
		}
	}

	/* Check options make sense together */

	switch (auth_cmd) {
		
	case AUTH_ADD_TOKEN:
		
		if (!got_sharename) {
			fprintf(stderr, "must specify sharename to add\n");
			return 1;
		}

		if (!got_user) {
			fprintf(stderr, "must specify username to add\n");
			return 1;
		}
		
		if (!got_workgroup) {
			fprintf(stderr, "must specify workgroup of user %s\n",
				username);
			return 1;
		}
		
		if (!got_pass) {
			fprintf(stderr, "must specify password for user "
				"%s\\%s\n", workgroup, username);
			return 1;
		}

		break;
	
	case AUTH_REMOVE_TOKEN:
		
		if (!got_sharename) {
			fprintf(stderr, "must specify sharename to remove\n");
			return 1;
		}

		if (got_user || got_workgroup || got_pass) {
			fprintf(stderr, "unecessary options specified\n");
			return 1;
		}

		break;

	case AUTH_FETCH_TOKEN:

		if (!got_sharename) {
			fprintf(stderr, "must specify sharename to fetch\n");
			return 1;
		}

		if (got_user || got_workgroup || got_pass) {
			fprintf(stderr, "uncessary options specified\n");
			return 1;
		}

		break;

	case AUTH_LIST_TOKENS:
	case AUTH_LIST_ALL_TOKENS:
	case AUTH_CLEAR_TOKENS:
	case AUTH_CLEAR_ALL_TOKENS:

		if (got_user || got_workgroup || got_pass || got_sharename) {
			fprintf(stderr, "unecessary options specified\n");
			return 1;
		}
		
		break;

	case -1:
		fprintf(stderr, "must specify one of -a, -r, or -c\n");
		return 1;

	default:
		fprintf(stderr, "unknown command %d\n", auth_cmd);
		return 1;
	}

	/* Execute requested command */

	switch (auth_cmd) {
	case AUTH_ADD_TOKEN:
		if (!add_token(sharename, username, workgroup, password)) {
			printf("error adding token\n");
			return 1;
		}
		break;

	case AUTH_REMOVE_TOKEN:
		if (!remove_token(sharename)) {
			printf("error removing token\n");
			return 1;
		}

		break;

	case AUTH_FETCH_TOKEN: {
		struct auth_token token;
		char *the_server, *the_share;

		the_server = sharename;

		if (the_server[0] == '/' && the_server[1] == '/') {
			the_server += 2;
		}

		the_share = strchr(the_server, '/');

		if (the_share) {
			the_share[0] = '\0';
			the_share++;
		}

		if (!fetch_token(getuid(), the_server, the_share, &token)) {
			printf("error fetching token\n");
			return 1;
		}

		printf("%d\n%s\n%s\n%s\n%s\n", token.uid, token.sharename,
		       token.workgroup, token.username, token.password);

		break;
	}

	case AUTH_CLEAR_TOKENS:
	case AUTH_CLEAR_ALL_TOKENS:
		if (!clear_tokens(auth_cmd == AUTH_CLEAR_ALL_TOKENS)) {
			printf("error clearing tokens\n");
			return 1;
		}

		break;

	case AUTH_LIST_TOKENS:
	case AUTH_LIST_ALL_TOKENS: {
		struct auth_token *tokens;
		int num_tokens;

		if (list_tokens(auth_cmd == AUTH_LIST_ALL_TOKENS, &tokens,
				 &num_tokens)) {
			int i;

			for (i = 0; i < num_tokens; i++) {
				printf("%d\n%s\n%s\n%s\n%s\n", 
				       tokens[i].uid, tokens[i].sharename,
				       tokens[i].workgroup, tokens[i].username,
				       tokens[i].password);
			}

			free(tokens);

		} else {
			printf("error listing tokens\n");
			return 1;
		}

		break;
	}

	default:
		fprintf(stderr, "unknown command %d\n", auth_cmd);
		return 1;
	}

	return 0;
}
