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

#include <popt.h>

#include "cryptsetup.h"
#include "setup.h"

#define DEVICE_PATH	"/dev/mapper"

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 = DEFAULT_KEY_SIZE;
static uint64_t opt_size = 0;
static uint64_t opt_offset = 0;
static uint64_t opt_skip = 0;

static char *dm_name;
static char *device;

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 struct action_type {
	const char *type;
	void (*handler)(int);
	int arg;
	int require_device;
	const char *desc;
} action_types[] = {
	{ "create",	action_create, 0, 1, N_("create device") },
	{ "remove",	action_remove, 0, 0, N_("remove device") },
	{ "reload",	action_create, 1, 1, N_("modify active device") },
	{ "resize",	action_resize, 0, 0, N_("resize active device") },
	{ "status",	action_status, 0, 0, N_("show device status") },
	{ NULL, NULL, 0, 0, NULL }
};

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

	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
		fprintf(stderr, ".\n");

	exit(1);
}

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

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

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

static void action_remove(int arg)
{
	struct crypt_options options = {
		.name = dm_name,
	};
	int r;

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

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

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

static void action_status(int arg)
{
	struct crypt_options options = {
		.name = dm_name,
	};
	int r;

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

	printf("%s/%s is active:\n", DEVICE_PATH, 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);

	if (options.cipher)
		free((void *)options.cipher);
	if (options.device)
		free((void *)options.device);
}

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;

		poptPrintHelp(popt_context, stdout, 0);

		fprintf(stdout, _(
			"\n"
			"<action> is one of:\n"));

		for(action = action_types; action->type; action++)
			fprintf(stdout, "\t%s - %s\n", action->type, gettext(action->desc));
		
		fprintf(stdout, _(
			"<name> is the device to create under %s\n"
			"<device> is the encrypted device\n"), DEVICE_PATH);
		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_("Show this help message"), 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") },
		POPT_TABLEEND
	};
	poptContext popt_context;
	struct action_type *action;
	char *aname;
	int r;

	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> <name> [<device>]"));

	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 (!(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));

	if (!(dm_name = (char *)poptGetArg(popt_context)))
		usage(popt_context, 1, _("Argument <name> missing."),
		      poptGetInvocationName(popt_context));

	device = (char *)poptGetArg(popt_context);
	if (!device && action->require_device)
		usage(popt_context, 1, _("Argument <device> missing."),
		      poptGetInvocationName(popt_context));

	if (opt_key_size % 8)
		usage(popt_context, 1,
		      _("Key size must be a multiple of 8 bits"),
		      poptGetInvocationName(popt_context));

	action->handler(action->arg);

	return 0;
}
