// SPDX-License-Identifier: LGPL-2.1-or-later
// SPDX-FileCopyrightText: 2008–2011 Jan Engelhardt
/*
 *	Internal diagnostic tool to debug pmt loop.c
 */
#include <errno.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <libHX/init.h>
#include <libHX/string.h>
#include "libcryptmount.h"
#include "pam_mount.h"

static unsigned int al_do_usetup;

static int al_setup(const char *prog, const char *arg1)
{
	char *dev;
	int ret;

	ret = ehd_loop_setup(arg1, &dev, EHD_LOSETUP_RW);
	if (ret == 0) {
		fprintf(stderr, "%s: error: no free loop devices\n",
		        HX_basename(prog));
		return EXIT_FAILURE;
	} else if (ret < 0) {
		fprintf(stderr, "%s: error: %s\n",
		        HX_basename(prog), strerror(-ret));
		return EXIT_FAILURE;
	} else {
		printf("Loop device assigned: %s\n", dev);
	}

	free(dev);
	return EXIT_SUCCESS;
}

static int al_usetup(const char *loop_dev)
{
	int ret;

	if ((ret = ehd_loop_release(loop_dev)) < 0)
		fprintf(stderr, "warning: loop_release: %s\n", strerror(-ret));
	return EXIT_SUCCESS;
}

int main(int argc, char **argv)
{
	static const struct HXoption options_table[] = {
		{.sh = 'u', .type = HXTYPE_NONE, .ptr = &al_do_usetup,
		 .help = "Unsetup"},
		HXOPT_AUTOHELP,
		HXOPT_TABLEEND,
	};
	struct HXopt6_result argp;
	int ret;

	ret = HX_init();
	if (ret <= 0) {
		fprintf(stderr, "HX_init: %s\n", strerror(errno));
		abort();
	}

	if (HX_getopt6(options_table, argc, argv, &argp,
	    HXOPT_USAGEONERR | HXOPT_ITER_ARGS) != HXOPT_ERR_SUCCESS)
		return false;
	if (argp.nargs != 1) {
		fprintf(stderr, "Usage: %s file\n", HX_basename(argv[0]));
		HX_getopt6_clean(&argp);
		return false;
	}
	if (al_do_usetup)
		ret = al_usetup(argp.uarg[0]);
	else
		ret = al_setup(argv[0], argp.uarg[0]);
	HX_getopt6_clean(&argp);
	HX_exit();
	return ret;
}
