/*
 * xtimer.c - timer
 * Copyright (C) 1997 by candy
 */
char rcsid[] = "$Id: qix.c,v 1.1 1993/11/06 16:54:54 candy Exp candy $";
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

#include <X11/Intrinsic.h>
#include <X11/StringDefs.h>
#include <X11/Xaw/Label.h>

#include <unistd.h> /* getpid(), fork() */
/*
#include <sys/time.h>
*/

static char *myname;
static time_t time0;
static int pause_time = 1000; /* milli-sec */
static Widget label;
static const char *pidfile;

#define PID_FILE "/tmp/xtimer.pid"

/*
 *
 */
static void
exitjob(void)
{
	if (pidfile != NULL) {
		remove(pidfile);
		pidfile = NULL;
	}
}/* exitjob */

/*
 *
 */
static void
sigtrap(int x)
{
	exit(2);
}/* sigtrap */

/*
 *
 */
static int
create_pid_file(const char *name)
{
	int err = -1;
	FILE *fp = fopen(name, "w");
	if (fp != NULL) {
		fprintf(fp, "%d\n", getpid());
		if (fclose(fp) == 0) {
			err = 0;
			pidfile = name;
			signal(SIGINT, sigtrap);
			signal(SIGQUIT, sigtrap);
			signal(SIGTERM, sigtrap);
			atexit(exitjob);
		}
	}
	return err;
}/* create_pid_file */

/*
 * タイムアウト処理。
 */
static void
timeout_proc(XtPointer p1, XtIntervalId* id)
{
	XtAppContext app_con = p1;
	time_t t = time(NULL) - time0;
	struct tm tm = *gmtime(&t);
	static char datestr[64];
	strftime(datestr, sizeof(datestr) - 1, "%H:%M:%S", &tm);
	datestr[sizeof(datestr) - 1] = '\0';
	XtVaSetValues(label, XtNlabel, datestr, NULL);
	XtAppAddTimeOut(app_con, pause_time, timeout_proc, app_con);
}/* timeout_proc  */

static char usage_msg[] =
	"XTimer V0.8086\n"
	"usage: %s [-toolkitoption ...]\n"
	"FILES:\t" PID_FILE " : pid file.\n"
	;

int
main(int argc, char *argv[])
{
	static String fallback_resources[] = {
		NULL
	};
#if 0
	static XtActionsRec actions[] = {
	};
#endif
	/*
	 * option
	 */
	struct app_resources_t {
	};
	static struct app_resources_t app_resources;
	static XtResource resources[] = {
	};
	static XrmOptionDescRec options[] = {
	};
	XtAppContext app_con;
	Widget toplevel;
	int ex = 1;
	myname = argv[0];
	toplevel = XtVaAppInitialize(&app_con, "XTimer", options, XtNumber(options), &argc, argv, fallback_resources, NULL);
	if (argc > 1) {
		fprintf(stderr, usage_msg, myname);
	}
	else {
		int pid = fork();
		if (pid < 0) {
			fprintf(stderr, "%s: ", myname);
			perror("fork");
		}
		else if (pid != 0) {
			exit(0);
		}
		if (create_pid_file(PID_FILE) < 0) {
			fprintf(stderr, "%s: ", myname);
			perror("cannot create pid file `" PID_FILE "'");
		}
		else {
			XtVaGetApplicationResources(toplevel, (caddr_t)&app_resources, resources, XtNumber(resources), NULL);
			label = XtVaCreateManagedWidget("label", labelWidgetClass, toplevel,
			XtNlabel, "00:00:00",
			NULL);
			time0 = time(NULL);
			XtRealizeWidget(toplevel);
			XtAppAddTimeOut(app_con, pause_time, timeout_proc, app_con);
			XtAppMainLoop(app_con);
			ex = 0;
		}
	}
	return ex;
}/* main */
