/*
	Demo for Endeavour interprocess command sending (no GTK or GUI
	code involved).
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <glib.h>
#include "../../include/disk.h"
#include "../edvcfg.h"
#include "../edvcfgfio.h"
#include "../edvcfglist.h"
#include "../edvinterps.h"
#include "../config.h"


static gint SendCommand(
	edv_cfg_item_struct *cfg_list,
	gchar **cmdv, gint cmdc
);

#ifdef PROG_USAGE_MESG
# undef PROG_USAGE_MESG
#endif
#define PROG_USAGE_MESG	"\
Usage: sendcmd <cmd1> [cmd2] [cmd3] [cmd4...]\n\
\n\
    Typical values for <cmd#> are as follows:\n\
\n\
	\"new_window file_browser <path>\"\n\
	\"new_window image_browser <path>\"\n\
	\"new_window archiver <path>\"\n\
	\"new_window recycle_bin\"\n\
	\"new_window properties <path>\"\n\
	\"new_window options\"\n\
	\"new_window customize\"\n\
	\"new_window devices\"\n\
	\"new_window mimetypes\"\n\
	\"new_window run_dialog\"\n\
\n\
    Remember to put \" characters around each <cmd#>.\n\
\n"


static gint SendCommand(
	edv_cfg_item_struct *cfg_list,
	gchar **cmdv, gint cmdc
)
{
	gint p = EDVInterPSGetLock(cfg_list);

	if(p == 0)
	{
	    fprintf(
		stderr,
		"Endeavour is not running or no lock link found.\n"
	    );
	    return(-2);
	}

	EDVInterPSSendCommand(cfg_list, p, cmdv, cmdc);

	return(0);
}

int main(int argc, char *argv[])
{
	const gchar *cstrptr, *arg_ptr;
	gchar cfg_file[PATH_MAX + NAME_MAX];
	edv_cfg_item_struct cfg_list[] = EDV_CONFIGURATION_LIST;


	/* Get value of environment variable HOME and prefix it to
	 * the standard path to the local recycled objects index file
	 * to obtain it's path as recycled_index_file.
	 */
	cstrptr = getenv("HOME");
	cstrptr = PrefixPaths(
	    (cstrptr != NULL) ? cstrptr : "/",
	    ".endeavour2/endeavour2.ini"
	);
	strncpy(
	    cfg_file,
	    (cstrptr != NULL) ? cstrptr : "/",
	    PATH_MAX + NAME_MAX
	);
	cfg_file[PATH_MAX + NAME_MAX - 1] = '\0';


	/* If no arguments then print help. */
	if(argc < 2)
	{
	    printf(PROG_USAGE_MESG);
	    return(0);
	}

	/* Begin parsing arguments, we know that we have at least two
	 * arguments.
	 */
	arg_ptr = argv[1];

	/* Help? */
	if(!strcmp(arg_ptr, "--help") ||
	  !strcmp(arg_ptr, "-help") ||
	  !strcmp(arg_ptr, "--h") ||
	  !strcmp(arg_ptr, "-h") ||
	  !strcmp(arg_ptr, "-?")
	)
	{
	    printf(PROG_USAGE_MESG);
	    return(0);
	}
	/* Version? */
	else if(!strcmp(arg_ptr, "--version") ||
	        !strcmp(arg_ptr, "-version")
	)
	{
	    printf(
PROG_NAME " Send Command " PROG_VERSION "\n" PROG_COPYRIGHT
	    );
	    return(0);
	}

	/* Get configuration and send command. */
	EDVCFGLoadFromFile(cfg_file, cfg_list);
	SendCommand(cfg_list, &argv[1], argc - 1);


	return(0);
}
