// ANSItex specific includes
load('ansitex/load/defs.js');
load('ansitex/load/funcs.js');

var options = loadOptions();

// Modes of operation:
// -s -p x -i y = To send a stored page via the msgbase
// {-s} -p x -i y -f file = To update (and optionally send) a page with new content
// -all details = to create a new page

// Import
send = (argv.indexOf('-s') >= 0);
// Page
p = getArg('-p','No page specified with -p',true);
// Index
i = getArg('-i','No index specified with -i',true);
// File to convert
file = getArg('-f','No file specified with -f',false);

frame = new TexFrame();
frame.load(pageStr({frame: p,index: i}));

if (! send || ! frame || file) {
	if (frame.page === null) {
		frame = new TexFrame();
		frame.frame = p;
		frame.index = i;
	}

	// Key
	key = getArg('-k','No index specified with -k',false);
	// Cost
	cost = getArg('-c','No index specified with -c',false);
	// Owner
	owner = getArg('-o','No owner specified with -o',false);
	// Owner
	type = getArg('-t','No type specified with -t',false);

	if (file) {
		f = new File(file);
		if (! f.exists || ! f.open('r')) {
			log(LOG_ERROR,'! ERROR: Unable to open ['+file+']');
			exit(1);
		}

		frame.content = base64_encode(f.read());
		f.close();
	}

	if (owner) {
		frame.owner = base64_encode(owner.replace(/\\1/g,"\1"));
	}

	if (key) {
		frame.key = key.split(',').map(function(t){return parseInt(t)});

		if (frame.key.length !== 10) {
			log(LOG_ERROR,'! ERROR: Must specify 10 keys with -k');
			exit(1);
		}
	}

	// Public
	if (argv.indexOf('-P') >= 0)
		frame.isPublic = true;

	if (argv.indexOf('-A') >= 0)
		frame.isAccessible = true;

	if (cost)
		frame.cost = cost;

	if (type)
		frame.type = type; // @todo validate this is a valid type.

	// Date
	frame.date = new Date().toISOString();

	// Final validation
	if (! frame.owner) {
		log(LOG_ERROR,'! ERROR: No owner specified ['+file+']');
		exit(1);
	}

	// Store the frame in file
	frame.save();
}

// @NOTE: We need to use a binary signature then base64 encode it, as mailers may strip 0x0a while messages are in transit.
if (send === 1 && options.gpg_key) {
	if (! file) {
		file = system.mods_dir+'ansitex/text/'+frame.page+'.tex';
	}

	if (! file_exists(file)) {
		log(LOG_ERROR,'! ERROR: File '+file+' doesnt exist?');
		exit(1);
	}

	if (file_exists(file+'.asc'))
		file_remove(file+'.asc')

	result = system.exec('gpg --homedir '+system.mods_dir+'ansitex/keys --clearsign --batch --local-user '+options.gpg_key+' -s '+file);
	w = new File(file+'.asc');

	if (w.open('r')) {
		msg = base64_encode(w.read());

	} else {
		log(LOG_ERROR,'! ERROR: Unable to send with GPG for '+frame.page + ' Error: '+w.error);
		exit(1);
	}

	w.close();

	msgBaseImport(null,frame.page,msg);
	printf('GPG Result: %s',result);
}