#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <inttypes.h>
#include <errno.h>
#include <assert.h>

#include <libcryptsetup.h>
#include <popt.h>

#include "../config.h"

#include "cryptsetup.h"

static int opt_verbose = 0;
static char *opt_cipher = DEFAULT_CIPHER;
static char *opt_hash = DEFAULT_HASH;
static int opt_verify_passphrase = 0;
static char *opt_key_file = NULL;
static unsigned int opt_key_size = 0;
static uint64_t opt_size = 0;
static uint64_t opt_offset = 0;
static uint64_t opt_skip = 0;
static int opt_readonly = 0;
static int opt_iteration_time = 1000;
static int opt_batch_mode = 0;
static int opt_version_mode = 0;
static int opt_timeout = 0;

static const char **action_argv;
static int action_argc;

static void action_create(int arg);
static void action_remove(int arg);
static void action_resize(int arg);
static void action_status(int arg);
static void action_luksFormat(int arg);
static void action_luksOpen(int arg);
static void action_luksDelKey(int arg);
static void action_luksAddKey(int arg);
static void action_isLuks(int arg);
static void action_luksUUID(int arg);
static void action_luksDump(int arg);

static struct action_type {
	const char *type;
	void (*handler)(int);
	int arg;
	int required_action_argc;
	const char *arg_desc;
	const char *desc;
} action_types[] = {
	{ "create",	action_create, 0, 2, N_("<name> <device>"), N_("create device") },
	{ "remove",	action_remove, 0, 1, N_("<name>"), N_("remove device") },
	{ "reload",	action_create, 1, 2, N_("<name>"), N_("modify active device") },
	{ "resize",	action_resize, 0, 1, N_("<name>"), N_("resize active device") },
	{ "status",	action_status, 0, 1, N_("<name>"), N_("show device status") },
	{ "luksFormat",	action_luksFormat, 0, 1, N_("<device> [<new key file>]"), N_("formats a LUKS device") },
	{ "luksOpen",	action_luksOpen, 0, 2, N_("<device> <name> "), N_("open LUKS device as mapping <name>") },
	{ "luksDelKey",	action_luksDelKey, 0, 2, N_("<device> <key slot>"), N_("wipes key with number <key slot> from LUKS device") },
	{ "luksAddKey",	action_luksAddKey, 0, 1, N_("<device> [<new key file>]"), N_("add key to LUKS device") },
	{ "luksUUID",	action_luksUUID, 0, 1, N_("<device>"), N_("print UUID of LUKS device") },
	{ "isLuks",	action_isLuks, 0, 1, N_("<device>"), N_("tests <device> for LUKS partition header") },
	{ "luksClose",	action_remove, 0, 1, N_("<name>"), N_("remove LUKS mapping") },
	{ "luksDump",	action_luksDump, 0, 1, N_("<device>"), N_("dump LUKS partition information") },
	{ NULL, NULL, 0, 0, NULL }
};

static void show_status(int errcode)
{
	char error[256];

	if(!errcode) {
	  fprintf(stderr, _("Command successful.\n"));
	  return;
	}

	crypt_get_error(error, sizeof(error));
	if (!opt_verbose) {
		char *error_ = strerror_r(errcode, error, sizeof(error));
		if (error_ != error) {
			strncpy(error, error_, sizeof(error));
			error[sizeof error - 1] = '\0';
		}
	}

	fprintf(stderr, _("Command failed"));
	if (*error)
		fprintf(stderr, ": %s\n", error);
	else
		fputs(".", stderr);
	return;
}

static void action_create(int reload)
{
	struct crypt_options options = {
		.name = action_argv[0],
		.device = action_argv[1],
		.cipher = opt_cipher,
		.hash = opt_hash,
		.key_file = opt_key_file,
		.key_size = ((opt_key_size)?opt_key_size:DEFAULT_KEY_SIZE)/8,
		.passphrase_fd = 0,	/* stdin */
		.flags = 0,
		.size = opt_size,
		.offset = opt_offset,
		.skip = opt_skip,
		.timeout = opt_timeout
	};
	int r;

	if (options.hash && strcmp(options.hash, "plain") == 0 || options.key_file)
		options.hash = NULL;
	if (opt_verify_passphrase)
		options.flags |= CRYPT_FLAG_VERIFY;
	if (opt_readonly)
		options.flags |= CRYPT_FLAG_READONLY;

	if (reload)
		r = crypt_update_device(&options);
	else
		r = crypt_create_device(&options);
	if (r < 0)
		show_status(-r);
}

static void action_remove(int arg)
{
	struct crypt_options options = {
		.name = action_argv[0],
	};
	int r;

	r = crypt_remove_device(&options);
	if (r < 0)
		show_status(-r);
}

static void action_resize(int arg)
{
	struct crypt_options options = {
		.name = action_argv[0],
		.size = opt_size,
	};
	int r;

	r = crypt_resize_device(&options);
	if (r < 0)
		show_status(-r);
}

static void action_status(int arg)
{
	struct crypt_options options = {
		.name = action_argv[0],
	};
	int r;

	r = crypt_query_device(&options);
	if (r < 0) {
		show_status(-r);
		return;
	}
	if (r == 0) {
		printf("%s/%s is inactive.\n", crypt_get_dir(), options.name);
		return;
	}

	printf("%s/%s is active:\n", crypt_get_dir(), options.name);
	printf("  cipher:  %s\n", options.cipher);
	printf("  keysize: %d bits\n", options.key_size * 8);
	printf("  device:  %s\n", options.device);
	printf("  offset:  %" PRIu64 " sectors\n", options.offset);
	printf("  size:    %" PRIu64 " sectors\n", options.size);
	if (options.skip)
		printf("  skipped: %" PRIu64 " sectors\n", options.skip);
	printf("  mode:    %s\n", (options.flags & CRYPT_FLAG_READONLY)
	                           ? "readonly" : "read/write");

	crypt_put_options(&options);
}

static int yesDialog(char *msg)
{
	int r = 0;
	if(isatty(0) && !opt_batch_mode) {
		char *answer=NULL;
		int size=0;
		fprintf(stderr,"\nWARNING!\n========\n");
		fprintf(stderr,"%s\n\nAre you sure? (Type uppercase yes): ",msg);
		getline(&answer,&size,stdin);
		if(strcmp(answer,"YES\n") == 0)
			r = 1;
		free(answer);
	} else
		r = 1;
	return r;
}

static void action_luksFormat(int arg)
{
	struct crypt_options options = {
		.key_size = (opt_key_size != 0 ? opt_key_size : DEFAULT_LUKS_KEY_SIZE) / 8,
		.device = action_argv[0],
		.cipher = opt_cipher,
		.new_key_file = action_argc > 1 ? action_argv[1] : NULL,
		.flags = opt_verify_passphrase ? CRYPT_FLAG_VERIFY : (!opt_batch_mode?CRYPT_FLAG_VERIFY_IF_POSSIBLE :  0),
		.iteration_time = opt_iteration_time,
		.timeout = opt_timeout,
	};

	int r = 0; char *msg = NULL;

	if(asprintf(&msg, _("This will overwrite data on %s irrevocably."), options.device) == -1) {
		fputs(_("memory allocation error in action_luksFormat"), stderr);
	} else {
		r = yesDialog(msg) ? crypt_luksFormat(&options) : -EINVAL;
		free(msg);
		show_status(-r);
	}
}

static void action_luksOpen(int arg)
{
	struct crypt_options options = {
		.name = action_argv[1],
		.device = action_argv[0],
		.key_file = opt_key_file,
		.timeout = opt_timeout,
	};
	int r; 

	opt_verbose = 1;
	options.flags = 0;
	if (opt_readonly)
		options.flags |= CRYPT_FLAG_READONLY;
	r = crypt_luksOpen(&options);
	show_status(-r);
}

static void action_luksDelKey(int arg)
{
	struct crypt_options options = {
		.device = action_argv[0],
		.key_slot = atoi(action_argv[1]),
	};
	int r; 

	opt_verbose = 1;
	if(LUKS_is_last_keyslot(options.device, options.key_slot) && 
	   !yesDialog(_("This is the last keyslot. Device will become unusable after purging this key."))) {
		r = -EINVAL;
	} else {
	        r = crypt_luksDelKey(&options);
	}
	show_status(-r);
}

static void action_luksAddKey(int arg)
{
	struct crypt_options options = {
		.device = action_argv[0],
		.key_file = opt_key_file,
		.new_key_file = action_argc>1?action_argv[1]:NULL,
		.key_file = opt_key_file,
		.flags = opt_verify_passphrase ? CRYPT_FLAG_VERIFY : (!opt_batch_mode?CRYPT_FLAG_VERIFY_IF_POSSIBLE : 0),
		.iteration_time = opt_iteration_time,
		.timeout = opt_timeout,
	};
	int r; 

	opt_verbose = 1;
	r = crypt_luksAddKey(&options);
	show_status(-r);
}

static void action_isLuks(int arg)
{
	struct crypt_options options = {
		.device = action_argv[0],
	};
	exit(crypt_isLuks(&options));
}

static void action_luksUUID(int arg)
{
	struct crypt_options options = {
		.device = action_argv[0],
	};
	int r; 

	r = crypt_luksUUID(&options);
	if (r < 0)
		show_status(-r);
}

static void action_luksDump(int arg)
{
	struct crypt_options options = {
		.device = action_argv[0],
	};
	int r; 

	r = crypt_luksDump(&options);
	if (r < 0)
		show_status(-r);
}

static void usage(poptContext popt_context, int exitcode,
                  const char *error, const char *more)
{
	poptPrintUsage(popt_context, stderr, 0);
	if (error)
		fprintf(stderr, "%s: %s\n", more, error);
	exit(exitcode);
}

static void help(poptContext popt_context, enum poptCallbackReason reason,
                 struct poptOption *key, const char * arg, void *data)
{
	if (key->shortName == '?') {
		struct action_type *action;

		fprintf(stdout, "%s\n",PACKAGE_STRING);

		poptPrintHelp(popt_context, stdout, 0);

		printf(_("\n"
			 "<action> is one of:\n"));

		for(action = action_types; action->type; action++)
			printf("\t%s %s - %s\n", action->type, _(action->arg_desc), _(action->desc));
		
		printf(_("\n"
			 "<name> is the device to create under %s\n"
			 "<device> is the encrypted device\n"
			 "<key slot> is the LUKS key slot number to modify\n"
			 "<key file> optional key file for the new key for luksAddKey action\n"),
			crypt_get_dir());
		exit(0);
	} else
		usage(popt_context, 0, NULL, NULL);
}                 

int main(int argc, char **argv)
{
	static char *popt_tmp;
	static struct poptOption popt_help_options[] = {
		{ NULL,    '\0', POPT_ARG_CALLBACK, help, 0, NULL,                         NULL },
		{ "help",  '?',  POPT_ARG_NONE,     NULL, 0, N_("Show this help message"), NULL },
		{ "usage", '\0', POPT_ARG_NONE,     NULL, 0, N_("Display brief usage"),    NULL },
		POPT_TABLEEND
	};
	static struct poptOption popt_options[] = {
		{ NULL,                '\0', POPT_ARG_INCLUDE_TABLE,                      popt_help_options,      0, N_("Help options:"),                                                   NULL },
		{ "verbose",           'v',  POPT_ARG_NONE,                               &opt_verbose,           0, N_("Shows more detailed error messages"),                              NULL },
		{ "cipher",            'c',  POPT_ARG_STRING | POPT_ARGFLAG_SHOW_DEFAULT, &opt_cipher,            0, N_("The cipher used to encrypt the disk (see /proc/crypto)"),          NULL },
		{ "hash",              'h',  POPT_ARG_STRING | POPT_ARGFLAG_SHOW_DEFAULT, &opt_hash,              0, N_("The hash used to create the encryption key from the passphrase"),  NULL },
		{ "verify-passphrase", 'y',  POPT_ARG_NONE,                               &opt_verify_passphrase, 0, N_("Verifies the passphrase by asking for it twice"),                  NULL },
		{ "key-file",          'd',  POPT_ARG_STRING,                             &opt_key_file,          0, N_("Read the key from a file (can be /dev/random)"),                   NULL },
		{ "key-size",          's',  POPT_ARG_INT    | POPT_ARGFLAG_SHOW_DEFAULT, &opt_key_size,          0, N_("The size of the encryption key"),                                  N_("BITS") },
		{ "size",              'b',  POPT_ARG_STRING,                             &popt_tmp,              1, N_("The size of the device"),                                          N_("SECTORS") },
		{ "offset",            'o',  POPT_ARG_STRING,                             &popt_tmp,              2, N_("The start offset in the backend device"),                          N_("SECTORS") },
		{ "skip",              'p',  POPT_ARG_STRING,                             &popt_tmp,              3, N_("How many sectors of the encrypted data to skip at the beginning"), N_("SECTORS") },
		{ "readonly",          'r',  POPT_ARG_NONE,                               &opt_readonly,          0, N_("Create a readonly mapping"),                                       NULL },
		{ "iter-time",         'i',  POPT_ARG_INT,                                &opt_iteration_time,    0, N_("PBKDF2 iteration time for LUKS (in ms)"),
		  N_("msecs") },
		{ "batch-mode",        'q',  POPT_ARG_NONE,                               &opt_batch_mode,        0, N_("Do not ask for confirmation"),                                     NULL },
		{ "version",        '\0',  POPT_ARG_NONE,                               &opt_version_mode,        0, N_("Print package version"),                                     NULL },
 		{ "timeout",           't',  POPT_ARG_INT,                                &opt_timeout,           0, N_("Timeout for interactive passphrase prompt (in seconds)"),          N_("secs") },
		POPT_TABLEEND
	};
	poptContext popt_context;
	struct action_type *action;
	char *aname;
	int r;
	const char *null_action_argv[] = {NULL};

	setlocale(LC_ALL, "");
	bindtextdomain(GETTEXT_PACKAGE, LOCALEDIR);
	textdomain(GETTEXT_PACKAGE);

	popt_context = poptGetContext(PACKAGE, argc, (const char **)argv,
	                              popt_options, 0);
	poptSetOtherOptionHelp(popt_context,
	                       N_("[OPTION...] <action> <action-specific>]"));

	while((r = poptGetNextOpt(popt_context)) > 0) {
		unsigned long long ull_value;
		char *endp;

		ull_value = strtoull(popt_tmp, &endp, 0);
		if (*endp || !*popt_tmp)
			r = POPT_ERROR_BADNUMBER;

		switch(r) {
			case 1:
				opt_size = ull_value;
				break;
			case 2:
				opt_offset = ull_value;
				break;
			case 3:
				opt_skip = ull_value;
				break;
		}

		if (r < 0)
			break;
	}

	if (r < -1)
		usage(popt_context, 1, poptStrerror(r),
		      poptBadOption(popt_context, POPT_BADOPTION_NOALIAS));
	if (opt_version_mode) {
	        printf("%s %s\n", PACKAGE_NAME, PACKAGE_VERSION);
		exit(0);
	}
	 
	if (opt_key_size % 8)
		usage(popt_context, 1,
		      _("Key size must be a multiple of 8 bits"),
		      poptGetInvocationName(popt_context));
	
	if (!(aname = (char *)poptGetArg(popt_context)))
		usage(popt_context, 1, _("Argument <action> missing."),
		      poptGetInvocationName(popt_context));
	for(action = action_types; action->type; action++)
		if (strcmp(action->type, aname) == 0)
			break;
	if (!action->type)
		usage(popt_context, 1, _("Unknown action."),
		      poptGetInvocationName(popt_context));

	action_argc = 0;
	action_argv = poptGetArgs(popt_context);
	/* Make return values of poptGetArgs more consistent in case of remaining argc = 0 */
	if(!action_argv) 
		action_argv = null_action_argv;
	
	/* Count args, somewhat unnice, change? */
	while(action_argv[action_argc] != NULL)
		action_argc++;

	if(action_argc < action->required_action_argc) {
		char buf[128];
		snprintf(buf, 128,_("%s: requires %s as arguments"), action->type, action->arg_desc);
		usage(popt_context, 1, buf,
		      poptGetInvocationName(popt_context));
	}	
	action->handler(action->arg);

	return 0;
}
