/*
 * Copyright (c)2004 The DragonFly Project.  All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 
 *   Redistributions of source code must retain the above copyright
 *   notice, this list of conditions and the following disclaimer.
 * 
 *   Redistributions in binary form must reproduce the above copyright
 *   notice, this list of conditions and the following disclaimer in
 *   the documentation and/or other materials provided with the
 *   distribution.
 * 
 *   Neither the name of the DragonFly Project nor the names of its
 *   contributors may be used to endorse or promote products derived
 *   from this software without specific prior written permission. 
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE. 
 */

/*
 * fn_subpart.c
 * Installer Function : Create Subpartitions.
 * $Id: fn_subpart.c,v 1.3 2004/07/11 07:29:57 cpressey Exp $
 */

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

#include <dfui/dfui.h>
#include <dfui/fspred.h>
#include <dfui/chain.h>
#include <dfui/dump.h>
#include <dfui/mem.h>

#include "diskutil.h"
#include "uiutil.h"
#include "commands.h"
#include "pathnames.h"
#include "functions.h"
#include "cmds.h"
#include "flow.h"

extern struct system_storage *ss;
extern struct dfui_connection *c;
extern char dfly_root[];

char *def_mountpt[7]  = {"/", "swap", "/var", "/tmp", "/usr", "/home", NULL};
long  def_capacity[7] = {128,    128,    128,    128,    256,      -1,    0};

int expert = 0;

/*
 * Given a set of subpartitions-to-be in the selected slice,
 * create them.
 */
int
create_subpartitions(void)
{
	struct subpartition *sp;
	struct commands *cmds;
	char *slice_dev_name, *subp_dev_name;
	int result = 0;

	cmds = commands_new();
	if (!is_file(INSTALLER_TEMP "install.disklabel.%ss%d",
	    ss->selected_disk->device,
	    ss->selected_slice->number)) {
		/*
		 * XXX It might make more sense for this to
		 * happen right after format_slice() instead.
		 */
		command_add(cmds, "disklabel -r %ss%d >"
		    INSTALLER_TEMP "install.disklabel.%ss%d",
		    ss->selected_disk->device,
		    ss->selected_slice->number,
		    ss->selected_disk->device,
		    ss->selected_slice->number);
	}

	/*
	 * Weave together a new disklabel out the of the 'virgin'
	 * disklabel, and the user's subpartition choices.
	 */
	command_add_function(cmds, cmd_weave_disklabel, (void *)ss,
	    "weave_disklabel()");

	/*
	 * Label the slice from the disklabel we just wove together.
	 */
	command_add(cmds, "disklabel -R -B -r %ss%d "
	    INSTALLER_TEMP "install.disklabel",
	    ss->selected_disk->device,
	    ss->selected_slice->number);

	/*
	 * Create a snapshot of the disklabel we just created
	 * for debugging inspection in the log.
	 */
	command_add(cmds, "disklabel %ss%d",
	    ss->selected_disk->device, ss->selected_slice->number);

	/*
	 * Remove the temporary disklabel.
	 */
	command_add(cmds, "rm -f " INSTALLER_TEMP "install.disklabel");

	/*
	 * Create filesystems on the newly-created subpartitions.
	 */
	for (sp = ss->selected_slice->subpartition_head; sp != NULL; sp = sp->next) {
		if (sp->is_swap)
			continue;
		command_add_function(cmds, cmd_maybe_makedev,
		    (void *)dfui_strdup(ss->selected_disk->device),
		    "maybe_makedev()");

		asprintf(&slice_dev_name, "%ss%d",
		    ss->selected_disk->device, ss->selected_slice->number);
		command_add_function(cmds, cmd_maybe_makedev,
		    (void *)slice_dev_name, "maybe_makedev()");

		asprintf(&subp_dev_name, "%ss%d%c",
		    ss->selected_disk->device, ss->selected_slice->number,
		    sp->letter);
		command_add_function(cmds, cmd_maybe_makedev,
		    (void *)subp_dev_name, "maybe_makedev()");

		command_add(cmds, "newfs%s %sdev/%ss%d%c",
		    sp->softupdates ? " -U" : "",
		    dfly_root,
		    ss->selected_disk->device,
		    ss->selected_slice->number,
		    sp->letter);
	}

	result = commands_execute(c, cmds);
	commands_free(cmds);
	return(result);
}

/*
 * +-------+------------+--------------+-----------------+-----------------+
 * | Mtpt  | Matt says  | FreeBSD says | I got away with | A tiny system   |
 * +-------+------------+--------------+-----------------+-----------------+
 * | /     |       256M |         100M |            256M |             64M |
 * | swap  |         1G | 2 or 3 * mem |  (4 * mem) 256M |   (1 * mem) 64M |
 * | /var  |       256M |          50M |            256M |             12M |
 * | /tmp  |       256M |          --- |            256M |             --- |
 * | /usr  | [4G to] 8G | (>160M) rest |              5G |            160M |
 * | /home |       rest |          --- |            3.5G |             --- |
 * +-------+------------+--------------+-----------------+-----------------+
 * | total |       10G+ |       ~430M+ |            9.5G |            300M |
 * +-------+------------+--------------+-----------------+-----------------+
 */

long
default_capacity(struct system_storage *ss, int mtpt)
{
	long swap;

	if (mtpt == MTPT_HOME)
		return(-1);

	swap = 2 * ss->ram;
	if (ss->ram > (ss->selected_slice->capacity / 2) ||
	    ss->selected_slice->capacity < 4096)
		swap = ss->ram;

	if (ss->selected_slice->capacity < DISK_MIN) {
		/*
		 * For the purposes of this installer:
		 * can't be done.  Sorry.
		 */
		return(-1);
	} else if (ss->selected_slice->capacity < 523) {
		switch (mtpt) {
		case MTPT_ROOT:	return(70);
		case MTPT_SWAP: return(swap);
		case MTPT_VAR:	return(32);
		case MTPT_TMP:	return(32);
		case MTPT_USR:	return(174);
		}
	} else if (ss->selected_slice->capacity < 1024) {
		switch (mtpt) {
		case MTPT_ROOT:	return(96);
		case MTPT_SWAP: return(swap);
		case MTPT_VAR:	return(64);
		case MTPT_TMP:	return(64);
		case MTPT_USR:	return(256);
		}
	} else if (ss->selected_slice->capacity < 4096) {
		switch (mtpt) {
		case MTPT_ROOT:	return(128);
		case MTPT_SWAP: return(swap);
		case MTPT_VAR:	return(128);
		case MTPT_TMP:	return(128);
		case MTPT_USR:	return(512);
		}
	} else if (ss->selected_slice->capacity < 10240) {
		switch (mtpt) {
		case MTPT_ROOT:	return(256);
		case MTPT_SWAP: return(swap);
		case MTPT_VAR:	return(256);
		case MTPT_TMP:	return(256);
		case MTPT_USR:	return(3072);
		}
	} else {
		switch (mtpt) {
		case MTPT_ROOT:	return(256);
		case MTPT_SWAP: return(swap);
		case MTPT_VAR:	return(256);
		case MTPT_TMP:	return(256);
		case MTPT_USR:	return(8192);
		}
	}
	/* shouldn't ever happen */
	return(-1);
}

int
check_capacity(struct slice *s)
{
	long min_capacity[7] = {70, 0, 8, 0, 174, 0, 0};
	long total_capacity = 0;
	struct subpartition *sp;
	int mtpt;
	
	if (subpartition_find(s, "/usr") == NULL) {
		min_capacity[MTPT_ROOT] += min_capacity[MTPT_USR];
	}

	for (sp = s->subpartition_head; sp != NULL;
	     sp = sp->next) {
		total_capacity += sp->capacity;
		for (mtpt = 0; def_mountpt[mtpt] != NULL; mtpt++) {
			if (strcmp(sp->mountpoint, def_mountpt[mtpt]) == 0 &&
			    min_capacity[mtpt] > 0 && sp->capacity > -1 &&
			    sp->capacity < min_capacity[mtpt]) {
				inform(	"WARNING: the %s subpartition should "
					"be at least %dM in size or you will "
					"risk running out of space during "
					"the installation.",
					sp->mountpoint, min_capacity[mtpt]);
			}
		}
	}

	if (total_capacity > s->capacity) {
		inform(	"The space allocated to all of your selected "
			"subpartitions (%dM) exceeds the total "
			"capacity of the selected primary partition "
			"(%dM). Remove some subpartitions or choose "
			"a smaller size for them and try again.",
			total_capacity, s->capacity);
		return(0);
	}

	return(1);
}

int
check_subpartition_selections(struct dfui_response *r, struct slice *s)
{
	struct dfui_dataset *ds;
	struct dfui_dataset *star_ds = NULL;
	char *mountpoint, *capstring;
	long capacity = 0;
	int softupdates;
	long fsize, bsize;
	int valid = 1;
	dfui_id_t m_id, c_id, su_id, fs_id, bs_id;
	struct chain *ch;
	int found_root = 0;

	m_id = dfui_id_new("mountpoint");
	c_id = dfui_id_new("capacity");
	su_id = dfui_id_new("softupdates");
	fs_id = dfui_id_new("fsize");
	bs_id = dfui_id_new("bsize");

	ch = chain_new();

	if ((ds = dfui_response_dataset_get_first(r)) == NULL) {
		inform("Please set up at least one subpartition.");
		valid = 0;
	}

	for (ds = dfui_response_dataset_get_first(r); valid && ds != NULL;
	     ds = dfui_dataset_get_next(ds)) {
#ifdef DEBUG
		dfui_dataset_dump(ds);
#endif
		mountpoint = dfui_dataset_get_value(ds, m_id);
		capstring = dfui_dataset_get_value(ds, c_id);

		if (expert) {
			softupdates =
			    (strcmp(dfui_dataset_get_value(ds, su_id), "Y") == 0);
			fsize = atol(dfui_dataset_get_value(ds, fs_id));
			bsize = atol(dfui_dataset_get_value(ds, bs_id));
		} else {
			softupdates = (strcmp(mountpoint, "/") == 0 ? 0 : 1);
			fsize = -1;
			bsize = -1;
		}

		if (chain_find(ch, mountpoint) != NULL) {
			inform(	"The same mount point cannot be specified for "
				"two different subpartitions.");
			valid = 0;
		}

		if (strcmp(mountpoint, "/") == 0) {
			found_root = 1;
		}

		if (strcmp(capstring, "*") == 0) {
			if (star_ds != NULL) {
				inform(	"You cannot have more than one subpartition "
					"with a '*' capacity (meaning 'use the remainder "
					"of the primary partition'.)");
				valid = 0;
			} else {
				star_ds = ds;
			}
		}
		
		if (!(!strcasecmp(mountpoint, "swap") || mountpoint[0] == '/')) {
			inform(	"Mount point must be either 'swap', or it must "
				 "start with a '/'.");
			valid = 0;
		}

		if (strpbrk(mountpoint, " \\\"'`") != NULL) {
			inform(	"Mount point may not contain the following "
				"characters: blank space, backslash, or "
				"single, double, or back quotes.");
			valid = 0;
		}
		
		if (strlen(capstring) == 0) {
			inform(	"A capacity must be specified.");
			valid = 0;
		}

		if (!string_to_capacity(capstring, &capacity)) {
			inform("Capacity must be either a '*' symbol to indicate "
			 "'use the rest of the primary partition', or it "
			 "must be a series of decimal digits ending with a "
			 "'M' (indicating megabytes) or a 'G' (indicating "
			 "gigabytes.)");
			valid = 0;
		}

		/*
		 * If we made it through that obstacle course, all is well.
		 */

		if (valid) {
			chain_add(ch, mountpoint);
		}
	}

	if (!found_root) {
		inform(	"You must include a / (root) subpartition.");
		valid = 0;
	}

	if (chain_length(ch) > 16) {
		inform(	"You cannot have more than 16 subpartitions "
			"on a single primary partition.  Remove some "
			"and try again.");
		valid = 0;
	}

	chain_free(ch);

	dfui_id_free(m_id);
	dfui_id_free(c_id);
	dfui_id_free(su_id);
	dfui_id_free(fs_id);
	dfui_id_free(bs_id);

	return(valid);
}

void
save_subpartition_selections(struct dfui_response *r, struct slice *s)
{
	struct dfui_dataset *ds;
	char *mountpoint;
	char *capstring;
	int softupdates;
	long fsize, bsize, capacity;
	int valid = 1;
	dfui_id_t m_id, c_id, su_id, fs_id, bs_id;

	m_id = dfui_id_new("mountpoint");
	c_id = dfui_id_new("capacity");
	su_id = dfui_id_new("softupdates");
	fs_id = dfui_id_new("fsize");
	bs_id = dfui_id_new("bsize");

	subpartitions_free(s);

	for (ds = dfui_response_dataset_get_first(r); valid && ds != NULL;
	     ds = dfui_dataset_get_next(ds)) {
		mountpoint = dfui_dataset_get_value(ds, m_id);
		capstring = dfui_dataset_get_value(ds, c_id);

		if (expert) {
			softupdates =
			    (strcmp(dfui_dataset_get_value(ds, su_id), "Y") == 0);
			fsize = atol(dfui_dataset_get_value(ds, fs_id));
			bsize = atol(dfui_dataset_get_value(ds, bs_id));
		} else {
			softupdates = (strcmp(mountpoint, "/") == 0 ? 0 : 1);
			fsize = -1;
			bsize = -1;
		}

		if (string_to_capacity(capstring, &capacity)) {
			subpartition_new(s, mountpoint, capacity,
			    softupdates, fsize, bsize);
		}
	}

	dfui_id_free(m_id);
	dfui_id_free(c_id);
	dfui_id_free(su_id);
	dfui_id_free(fs_id);
	dfui_id_free(bs_id);
}

void
populate_create_subpartitions_form(struct dfui_form *f, struct slice *s)
{
	struct subpartition *sp;
	struct dfui_dataset *ds;
	char temp[32];
	int mtpt;
	long capacity;

	if (s->subpartition_head != NULL) {
		/*
		 * The user has already given us their subpartition
		 * preferences, so use them here.
		 */
		for (sp = s->subpartition_head; sp != NULL; sp = sp->next) {
			ds = dfui_dataset_new();
			dfui_dataset_celldata_add(ds, dfui_id_new("mountpoint"),
			    sp->mountpoint);
			dfui_dataset_celldata_add(ds, dfui_id_new("capacity"),
			    capacity_to_string(sp->capacity));
			if (expert) {
				dfui_dataset_celldata_add(ds, dfui_id_new("softupdates"),
				    sp->softupdates ? "Y" : "N");
				snprintf(temp, 32, "%ld", sp->fsize);
				dfui_dataset_celldata_add(ds, dfui_id_new("fsize"),
				    temp);
				snprintf(temp, 32, "%ld", sp->bsize);
				dfui_dataset_celldata_add(ds, dfui_id_new("bsize"),
				    temp);
			}
			dfui_form_dataset_add(f, ds);
		}
	} else {
		/*
		 * Otherwise, populate the form with datasets representing
		 * reasonably-calculated defaults.  The defaults are chosen
		 * based on the slice's total capacity and the machine's
		 * total physical memory (for swap.)
		 */
		for (mtpt = 0; def_mountpt[mtpt] != NULL; mtpt++) {
			capacity = default_capacity(ss, mtpt);
			ds = dfui_dataset_new();
			dfui_dataset_celldata_add(ds, dfui_id_new("mountpoint"),
			    def_mountpt[mtpt]);
			dfui_dataset_celldata_add(ds, dfui_id_new("capacity"),
			    capacity_to_string(capacity));
			if (expert) {
				dfui_dataset_celldata_add(ds, dfui_id_new("softupdates"),
				    strcmp(def_mountpt[mtpt], "/") != 0 ? "Y" : "N");
				dfui_dataset_celldata_add(ds, dfui_id_new("fsize"),
				    capacity < 1024 ? "1024" : "4096");
				dfui_dataset_celldata_add(ds, dfui_id_new("bsize"),
				    capacity < 1024 ? "8192" : "16384");
			}
			dfui_form_dataset_add(f, ds);
		}
	}
}

int
warn_subpartition_selections(struct slice *s)
{
	int valid = 0;
	char omit[256];

	valid = check_capacity(s);
	strcpy(omit, "");
	if (valid && subpartition_find(s, "/var") == NULL) {
		strcat(omit, "/var ");
	}
	if (valid && subpartition_find(s, "/usr") == NULL) {
		strcat(omit, "/usr ");
	}
	if (strlen(omit) > 0) {
		switch (dfui_be_present_dialog(c, "Really omit?",
		    "Omit Subpartition(s)|Return to Create Subpartitions",
		    "You have elected to not have the following "
		    "subpartition(s):\n\n%s "
		    "\n\nFiles destined for these subpartition(s) "
		    "will be copied into a plain directoy in the / (root) "
		    "subpartition instead.\n\nThis is not recommended. "
		    "Is this really what you want to do?", omit)) {
		case 1:
			valid = 1;
			break;
		case 2:
			valid = 0;
			break;
		default:
			abort_backend();
		}
	}

	return(!valid);
}

struct dfui_form *
make_create_subpartitions_form(void)
{
	struct dfui_form *f;
	struct dfui_field *fi;

	f = dfui_form_create(
		"create_subpartitions",
		"Create Subpartitions",
		"Set up the subpartitions (also known as just `partitions' "
		"in BSD tradition) you want to have on this primary "
		"partition.\n\n"
		"For Capacity, use 'M' to indicate megabytes, 'G' to "
		"indicate gigabytes, or a single '*' to indicate "
		"'use the remaining space on the primary partition'.",

		"Subpartitions further divide a primary partition for "
		"use with DragonFly.  Some reasons you may want "
		"a set of subpartitions are:\n\n"
		"- you want to restrict how much data can be written "
		  "to certain parts of the primary partition, to quell "
		  "denial-of-service attacks; and\n"
		"- you want to speed up access to data on the disk."
		"",

		"h",	"special", 	"nympha_create_subpartitions",
		"h",	"minimum_width","64",

		"f",	"mountpoint", 	"Mountpoint", "", "",
		"f",	"capacity", 	"Capacity", "", "",

		"a",	"ok", 		"Accept and Create", "", "",
		"a",	"cancel", 
			    (ss->selected_disk->we_formatted ?
			    "Return to Select Disk" :
			    "Return to Select Primary Partition"), "", "",
		NULL
	);

	dfui_form_set_multiple(f, 1);
	dfui_form_set_extensible(f, 1);

	if (expert) {
		fi = dfui_form_field_add(f, dfui_id_new("softupdates"),
		    dfui_info_new("Softupdates?", "", ""));
		dfui_field_hint_add(fi, "control", "checkbox");
		fi = dfui_form_field_add(f, dfui_id_new("fsize"),
		    dfui_info_new("Frag Size", "", ""));
		fi = dfui_form_field_add(f, dfui_id_new("bsize"),
		    dfui_info_new("Block Size", "", ""));
		dfui_form_action_add(f, dfui_id_new("switch"),
		    dfui_info_new("Switch to Normal Mode", "", ""));
	} else {
		dfui_form_action_add(f, dfui_id_new("switch"),
		    dfui_info_new("Switch to Expert Mode", "", ""));
	}

	return(f);
}

/*
 * Returns:
 *	-1 = the form should be redisplayed
 *	 0 = failure, function is over
 *	 1 = success, function is over
 */
int
show_create_subpartitions_form(struct dfui_form *f)
{
	struct dfui_response *r;
	struct dfui_dataset *ds;

	for (;;) {
		if (dfui_form_dataset_get_first(f) == NULL) {
			populate_create_subpartitions_form(f, ss->selected_slice);
		}

		if (!dfui_be_present(c, f, &r)) abort_backend();
	
		if (dfui_id_is(dfui_response_get_action_id(r), "cancel")) {
			dfui_response_free(r);
			return(0);
		} else if (dfui_id_is(dfui_response_get_action_id(r), "switch")) {
			if (check_subpartition_selections(r, ss->selected_slice)) {
				save_subpartition_selections(r, ss->selected_slice);
				expert = expert ? 0 : 1;
				dfui_response_free(r);
				return(-1);
			}
		} else {
			if (check_subpartition_selections(r, ss->selected_slice)) {
				save_subpartition_selections(r, ss->selected_slice);
				if (!warn_subpartition_selections(ss->selected_slice)) {
					if (!create_subpartitions()) {
						inform(	"The subpartitions you chose were "
							"not correctly created, and the "
							"primary partition may "
							"now be in an inconsistent state. "
							"We recommend re-formatting it "
							"before proceeding.");
						dfui_response_free(r);
						return(0);
					} else {
						dfui_response_free(r);
						return(1);
					}
				}
			}
		}
		
		dfui_form_datasets_free(f);
		/* dfui_form_datasets_add_from_response(f, r); */
		for (ds = dfui_response_dataset_get_first(r); ds != NULL;
		     ds = dfui_dataset_get_next(ds)) {
			dfui_form_dataset_add(f, dfui_dataset_dup(ds));
		}
	}
}

/*
 * fn_create_subpartitions: let the user specify what subpartitions they
 * want on the disk, how large each should be, and where it should be mounted.
 */
int
fn_create_subpartitions(void)
{
	struct dfui_form *f;
	int done = 0, result = 0;

	while (!done) {
		f = make_create_subpartitions_form();
		switch (show_create_subpartitions_form(f)) {
		case -1:
			done = 0;
			break;
		case 0:
			done = 1;
			result = 0;
			break;
		case 1:
			done = 1;
			result = 1;
			break;
		}
		dfui_form_free(f);
	}

	return(result);
}
