/*
Copyright 1990-2003 Sun Microsystems, Inc. All Rights Reserved.

Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions: The above copyright notice and this
permission notice shall be included in all copies or substantial
portions of the Software.


THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE OPEN GROUP OR SUN MICROSYSTEMS, INC. BE LIABLE
FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH
THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE EVEN IF
ADVISED IN ADVANCE OF THE POSSIBILITY OF SUCH DAMAGES.


Except as contained in this notice, the names of The Open Group and/or
Sun Microsystems, Inc. shall not be used in advertising or otherwise to
promote the sale, use or other dealings in this Software without prior
written authorization from The Open Group and/or Sun Microsystems,
Inc., as applicable.


X Window System is a trademark of The Open Group

OSF/1, OSF/Motif and Motif are registered trademarks, and OSF, the OSF
logo, LBX, X Window System, and Xinerama are trademarks of the Open
Group. All other trademarks and registered trademarks mentioned herein
are the property of their respective owners. No right, title or
interest in or to any trademark, service mark, logo or trade name of
Sun Microsystems, Inc. or its licensors is granted.

*/

#pragma ident	"$Id$"

#include <unistd.h>
#include <stdlib.h>
#include <signal.h>
#if defined(USE_CDE_HELP)
#include <X11/Intrinsic.h>
#include <X11/StringDefs.h>
#else /* USE_CDE_HELP */
#include <sys/types.h>
#include <sys/wait.h>
#endif /* USE_CDE_HELP */

#include "iiimpAux.h"
#include "xaux_ext_help.h"

#if defined(USE_CDE_HELP)

#if defined(USE_DTACTIONINVOKE)
#include <Dt/Dt.h>
#include <Dt/Action.h>

static void DbReloadProc(XtPointer cd);

#else /* defined(USE_DTACTIONINVOKE) */

#define DTACTION_CMD    "/usr/dt/bin/dtaction"

static int help_available = 0;
static char tmp_file[256];

void
HelpCleanup()
{
    if (help_available) {
        unlink(tmp_file);
    }
}

void
HelpSinalHandler(int unused)
{
    HelpCleanup();
    exit(1);
}

int
HelpXIOErrorHandler(Display * dpy)
{
    HelpCleanup();
    return 0;
}
#endif /* defined(USE_DTACTIONINVOKE) */

typedef struct _RmDatabase {
    char *help_basepath;
} RmDatabase;

static RmDatabase rdb;

static XtResource rdb_items[] = {
  {"helpBasepath", "HelpBasepath", XtRString, sizeof(char*),
   offsetof(RmDatabase, help_basepath), XtRString,
   (XPointer)DEFAULT_HELP_PATH
   },
};

void
HelpInit(
	Widget shell,
        char *ApplicationClass,
	int argc,
	char **argv
)
{
#if defined(USE_DTACTIONINVOKE)
    if (DtInitialize(XtDisplay(shell), shell, argv[0], ApplicationClass)==False) {
        /* DtInitialize() has already logged an appropriate error msg */
        exit(-1);
    }

    /* Load the filetype/action databases */
    DtDbLoad();

    /* Notice changes to the database without needing to restart application */
    DtDbReloadNotify(DbReloadProc, NULL);
#else /* defined(USE_DTACTIONINVOKE) */
    int i;
    char *tmp_dir;
    char tmp_tmp_file[256];

    if (help_available) {
        return;
    }
    XtGetApplicationResources(shell,
                              &rdb, rdb_items, 1,
                              NULL, 0);

    if (access(DTACTION_CMD, X_OK) != 0) {
        return;
    }
    tmp_dir = getenv("HOME");
    if (!tmp_dir) {
        return;
    }

    /* check tmp file exists or not */
    for(i=0;i<10;i++){
        sprintf(tmp_tmp_file, "%s/.dt/tmp/%s.%s", tmp_dir,
            strrchr(ApplicationClass, '.') + 1, "XXXXXX");
        mktemp(tmp_tmp_file);
        if (access(tmp_tmp_file, F_OK) != 0) {
            strcpy(tmp_file, tmp_tmp_file);
	    help_available = 1;
            break;
        }
    }

    if(!help_available){
	return;
    }

    /* At shoutdown of user session */
    XSetIOErrorHandler(HelpXIOErrorHandler);

    signal(SIGKILL, HelpSinalHandler);
    signal(SIGTERM, HelpSinalHandler);
    signal(SIGHUP, HelpSinalHandler);
#endif /* defined(USE_DTACTIONINVOKE) */

    XtGetApplicationResources(shell,
                                &rdb, rdb_items, 1,
                                NULL, 0);

#if defined(DEBUG_XAUX)
   printf("basepath = %s\n", rdb.help_basepath);
#endif /* defined(DEBUG_XAUX) */
}

#if defined(USE_DTACTIONINVOKE)
static void DbReloadProc(XtPointer cd)
{
    /* Pick up any dynamic changes to the database files */
    DtDbLoad();
}
#endif /* defined(USE_DTACTIONINVOKE) */

void
HelpInvoke(
	Widget toplevel,
	char *path_
)
{
#if defined(USE_DTACTIONINVOKE)
    DtActionArg *ap = NULL;
    int nap = 0;
    DtActionInvocationID actionId;
    char path[256];

    sprintf(path, "%s%s", rdb.help_basepath, path_);

#if defined(DEBUG_XAUX)
    printf("actual path = %s\n", path);
#endif /* defined(DEBUG_XAUX) */

    if (path != NULL){
        ap = (DtActionArg*) XtCalloc(1, sizeof(DtActionArg));

        ap[0].argClass = DtACTION_BUFFER;
        ap[0].u.buffer.bp = (void*)path;
        ap[0].u.buffer.size = strlen(path);
        ap[0].u.buffer.type = NULL;
        ap[0].u.buffer.name = NULL;
        ap[0].u.buffer.writable = False;

        nap = 1;
    }

    /* Invoke the specified action */
    actionId = DtActionInvoke(toplevel,"SDtWebClient",ap,nap,NULL,NULL,NULL,True,NULL,NULL);
#else /* defined(USE_DTACTIONINVOKE) */
    FILE *fp;
    pid_t pid;

    if (!help_available) {
        return;
    }
    if (!path_) {
        return;
    }
    if ((fp = fopen(tmp_file, "w")) == NULL) {
        return;
    }
    fprintf(fp, "%s%s\n", rdb.help_basepath, path_);
    fclose(fp);

    pid = fork1();

    if (pid == (pid_t) (-1)) {
        return;
    } else if (0 == pid) {
        execl(DTACTION_CMD, "dtaction",
              "SDtWebClient", tmp_file, NULL);
        _exit(1);
    }
    return;
#endif /* defined(USE_DTACTIONINVOKE) */
}

#else /* USE_CDE_HELP */

void
HelpInvoke(
        char *path
)
{
    char *browser;
    char *basepath;

    pid_t pid, pid2;

    if (!path) {
      return;
    }

#ifdef linux
    pid = fork();
#else
    pid = fork1();
#endif

#if defined(USE_GNOME_HELP)
    browser = "/usr/lib/im/locale/ja/sampleja4/help/help-handler";
#else /* USE_GNOME_HELP */
    if (getenv("HTT_HELP_BROWSER")){
      browser = getenv("HTT_HELP_BROWSER");
    } else {
      browser = "/usr/bin/netscape";
    }
#endif /* USE_GNOME_HELP */

    if (getenv("HTT_HELP_PATH")){
      basepath = getenv("HTT_HELP_PATH");
    } else {
      basepath = DEFAULT_HELP_PATH;
    }

    if (pid == (pid_t) (-1)) {
        return;
    } else if (0 == pid) {
        pid2 = fork();
        if(pid2 == -1) {
            _exit(1);
        } else if(pid2 == 0) {
	    char *help = (char*)malloc(strlen(basepath) + strlen(path) +1 );
	    sprintf(help, "%s%s", basepath, path);
	    execl(browser, browser, help, NULL);
	    free(help);
            _exit(1);
        } else {
            _exit(0);
        }
    } else {
        waitpid(pid, NULL, 0);
    }
    return;
}

#endif /* USE_CDE_HELP */
