#ident "@(#)main.c	1.12 91/09/14 SMI"


/*
 *
 * Copyright (c) 1991 by Sun Microsystems, Inc.
 *
 *
 * This file is a product of Sun Microsystems, Inc. and is provided for
 * unrestricted use provided that this legend is included on all tape
 * media and as a part of the software program in whole or part.  Users
 * may copy or modify this file without charge, but are not authorized to
 * license or distribute it to anyone else except as part of a product
 * or program developed by the user.
 * 
 * THIS FILE IS PROVIDED AS IS WITH NO WARRANTIES OF ANY KIND INCLUDING THE
 * WARRANTIES OF DESIGN, MERCHANTIBILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE OR TRADE PRACTICE.
 * 
 * This file is provided with no support and without any obligation on the
 * part of Sun Microsystems, Inc. to assist in its use, correction,
 * modification or enhancement.
 * 
 * SUN MICROSYSTEMS, INC. SHALL HAVE NO LIABILITY WITH RESPECT TO THE
 * INFRINGEMENT OF COPYRIGHTS, TRADE SECRETS OR ANY PATENTS BY THIS FILE
 * OR ANY PART THEREOF.
 * 
 * In no event will Sun Microsystems, Inc. be liable for any lost revenue
 * or profits or other special, indirect and consequential damages, even
 * if Sun has been advised of the possibility of such damages.
 * 
 * Sun Microsystems, Inc.
 * 2550 Garcia Avenue
 * Mountain View, California  94043
 */


#include <sys/types.h>
#include <sys/time.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <assert.h>
#include <fcntl.h> 
#include <signal.h>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <wire/wire.h>
#include "clock.h"


#define VERSION_STRING "version 2.0"


#define allocate_tag(psname, cproc, data) {	\
    int tag = wire_AllocateTags(1);		\
    extern void cproc(int, caddr_t);		\
    ps_set_tag(psname, tag);			\
    wire_RegisterTag(tag, cproc, data);		\
}


struct clockargs {
    char *version_present;

    char *reload_present;

    char *seconds_present;

    char *date_present;

    char *face;

    char *timezone;

    char *alarm_setting;
    int alarm_hour;
    int alarm_min;
    char *alarm_cmd;

    char *hour_cmd;
};


char *progname;
struct clockargs args;
wire_Wire ps_wire;
int clock_inst;
char tzenvbuf[1024];
char curtz[1024];


int ready = FALSE;

int want_date = FALSE;
int last_month = -1;
int last_day = -1;
int last_dow = -1;

int last_h = -1;
int last_m = -1;

int want_seconds = FALSE;
int last_s = -1;


void
set_tz(char *tz)
{
    strcpy(curtz, tz);
    sprintf(tzenvbuf, "TZ=%s", tz);
    putenv(tzenvbuf);
    tzset();
}


void
init_tz()
{
    char *c;

    c = getenv("TZ");

    if (c == NULL) {
        set_tz("localtime");
    } else {
        set_tz(c);
    }
}


void
death_handler(wire_Wire w)
{
    wire_Close(w);
    exit(0);
}


void
ready_handler(int tag, caddr_t data)
{
    int ob;

    ob = wire_ReadInt();

    ready = TRUE;
}


void
props_handler(int tag, caddr_t data)
{
    int secs;
    int date;
    char tz[1024];
    char *c;
    int ob;

    ob = wire_ReadInt();
    secs = wire_ReadInt();
    date = wire_ReadInt();
    c = wire_ReadString(tz);

    if (secs != want_seconds) {
        want_seconds = secs;
        last_s = -1;
    }

    if (date != want_date) {
        want_date = date;
        last_month = -1;
        last_day = -1;
        last_dow = -1;
    }

    if (strcmp(c, curtz) != 0) {
        last_month = -1;
        last_day = -1;
        last_dow = -1;
        last_h = -1;
        last_m = -1;
        last_s = -1;

        set_tz(c);
    }
}


void
msg_handler(int tag, caddr_t data)
{
    int fatal;
    char msg[1024];
    char *c;
    int ob;

    ob = wire_ReadInt();
    fatal = wire_ReadInt();
    c = wire_ReadString(msg);

    fprintf(stderr, "%s: %s\n", progname, c);

    if (fatal)
        exit(1);
}


void
cmd_handler(int tag, caddr_t data)
{
    char buf[1024];
    char *c;
    int pid;
    int ob;

    ob = wire_ReadInt();
    c = wire_ReadString(buf);

    if (strcmp(c, "") == 0)
        return;

    if ((pid = fork()) == 0) {
        int fd;
        char *sh;

        wire_Close(ps_wire);

        fd = open("/dev/null", O_RDONLY);
        assert(fd > 2);
        dup2(fd, 0);
        close(fd);

        fd = open("/dev/console", O_WRONLY);
        assert(fd > 2);
        dup2(fd, 1);
        dup2(fd, 2);
        close(fd);

        sh = getenv("SHELL");
        if (sh == NULL)
            sh = "/bin/sh";

        execl(sh, sh, "-ce", c, NULL);

        fprintf(stderr, "%s: could not execute shell.\n", progname);
        exit(1);
    }

    if (pid < 0) {
        fprintf(stderr, "%s: could not fork process.\n", progname);
        return;
    }
}


void
quit_handler(int tag, caddr_t data)
{
    int ob;

    ob = wire_ReadInt();

    death_handler(ps_wire);
}


void
child_handler(int sig)
{
    int sts;
    int pid;

    while (1) {
        pid = waitpid(-1, &sts, WNOHANG);
        if (pid <= 0)
            return;
    }
}

void
send_tags(void)
{
    ps_namedictbegin("clocktags");

    allocate_tag("ready_tag", ready_handler, NULL);
    allocate_tag("props_tag", props_handler, NULL);
    allocate_tag("msg_tag", msg_handler, NULL);
    allocate_tag("cmd_tag", cmd_handler, NULL);
    allocate_tag("quit_tag", quit_handler, NULL);

    ps_dictenddef();
    ps_flush_PostScript();
}


void
send_args(void)
{
    char *cmd;

    wire_ExecuteArguments();

    ps_namedictbegin("clockargs");

    cmd = progname;

    /* remove slashes from cmd unless path is absolute */

    if (cmd[0] != '/') {
        char *t;
        t = strrchr(cmd, '/');
        if (t != NULL)
            cmd = t + 1;
    }

    ps_namestringdef("command", cmd);

    if (args.seconds_present) {
        ps_namebooleandef("seconds", TRUE);
    } else {
        ps_namebooleandef("seconds", FALSE);
    }

    if (args.date_present) {
        ps_namebooleandef("date", TRUE);
    } else {
        ps_namebooleandef("date", FALSE);
    }

    ps_namestringdef("face", args.face);

    ps_namestringdef("timezone", args.timezone);
    if (strcmp(args.timezone, curtz) != 0) {
        set_tz(args.timezone);
    }

    ps_namestringdef("setting", args.alarm_setting);
    ps_nameintdef("hour", args.alarm_hour);
    ps_nameintdef("minute", args.alarm_min);
    ps_namestringdef("alarm_command", args.alarm_cmd);

    ps_namestringdef("hour_command", args.hour_cmd);

    ps_dictenddef();
    ps_flush_PostScript();
}


int
begin_packages(int reload)
{
    int sync_tag = wire_AllocateTags(1);
    int sts;

    ps_begin_system_packages(sync_tag, &sts);
    if (sts) {
        return sts;
    }

    if (!reload) {
        ps_begin_my_package(FALSE, sync_tag, &sts);
    } else {
        sts = 1;
    }

    if (sts) {
        ps_send_my_package(reload, sync_tag, &sts);
        if (sts) {
            return 1;
        }

        ps_begin_my_package(TRUE, sync_tag, &sts);
    }

    return sts;
}


void
get_time(int *month, int *day, int *dow, int *h, int *m, int *s)
{
    time_t cl;
    struct tm *daytime;

    time(&cl);
    daytime = localtime(&cl);

    *month = daytime->tm_mon;
    *day = daytime->tm_mday;
    *dow = daytime->tm_wday; /* 0 = sunday */
    *h = daytime->tm_hour;
    *m = daytime->tm_min;
    *s = daytime->tm_sec;
}


void
init_clock(void)
{
    int trash;

    clock_inst = wire_AllocateTokens(ps_wire, 1);

    get_time(&trash, &trash, &trash,
        &last_h, &last_m, &trash);

    ps_init_clock(clock_inst, last_h, last_m);

    ps_flush_PostScript();
}


void
clock_loop(void)
{
    while (TRUE) {
        struct timeval wait_tv;
        int this_month;
        int this_day;
        int this_dow;
        int this_h;
        int this_m;
        int this_s;

        if (want_seconds) {
            wait_tv.tv_sec = 0;
            wait_tv.tv_usec = 200000;
        } else {
            wait_tv.tv_sec = 1;
            wait_tv.tv_usec = 0;
        }

        (void) wire_Notify(&wait_tv);

        if (!ready)
            continue;

        get_time(&this_month, &this_day, &this_dow,
            &this_h, &this_m, &this_s);

        if (want_date) {
            if (this_day != last_day || this_month != last_month) {
                ps_set_date(clock_inst, this_month, this_day, this_dow);
                last_month = this_month;
                last_day = this_day;
                last_dow = this_dow;
                last_h = -1;
                last_m = -1;
            }
        }

        if (this_m != last_m || this_h != last_h) {
            if (want_seconds) {
                ps_set_time(clock_inst, this_h, this_m);
                last_s = -1;
            } else {
                ps_change_time(clock_inst, this_h, this_m);
                ps_flush_PostScript();
            }
            last_h = this_h;
            last_m = this_m;
        }

        if (want_seconds) {
            if (this_s != last_s) {
                ps_change_secs(clock_inst, this_s);
                ps_flush_PostScript();
                last_s = this_s;
            }
        }
    }
}


int
main(int argc, char *argv[])
{
    wire_AddOption("-v %-",
        (caddr_t) &args.version_present, NULL,
        "-v - print clock version and exit");

    wire_AddOption("-r %-",
        (caddr_t) &args.reload_present, NULL,
        "-r - force reload of clock software");

    wire_AddOption("-seconds %-",
        (caddr_t) &args.seconds_present, NULL,
        "-seconds - display second hand");

    wire_AddOption("-date %-",
        (caddr_t) &args.date_present, NULL,
        "-date - display date");

    wire_AddOption("-face %s",
        (caddr_t) &args.face, NULL,
        "-face name - select clock face");

    wire_AddOption("-timezone %s",
        (caddr_t) &args.timezone, NULL,
        "-timezone name - select timezone");

    wire_AddOption("-alarm %s %d %d %s",
        (caddr_t) &args.alarm_setting, NULL,
        "-alarm setting hour min cmd - set alarm");

    wire_AddOption("-hour %s",
        (caddr_t) &args.hour_cmd, NULL,
        "-hour cmd - set hour command");

    /* set defaults */

    progname = argv[0];

    memset((char *) &args, 0, sizeof(args));

    args.face = "";

    init_tz();
    args.timezone = curtz;

    args.alarm_setting = "";
    args.alarm_hour = 0;
    args.alarm_min = 0;
    args.alarm_cmd = "";

    args.hour_cmd = "";

    if (!wire_ParseArguments(argc, argv)) {
        exit(1);
    }

    if (args.version_present) {
        printf("%s: %s\n", progname, VERSION_STRING);
        exit(0);
    }

    ps_wire = wire_Open(wire_Display());

    if (ps_wire == wire_INVALID_WIRE) {
        fprintf(stderr, "%s: could not connect to server (%s).\n",
            progname, wire_ErrorString());
        exit(1);
    }

    wire_Problems(ps_wire,
        (wire_Handler) death_handler,
            (wire_Handler) wire_DiseaseDefault,
                (wire_Handler) wire_UnknownTagDefault);

    ps_set_processname();

    send_tags();

    send_args();

    if (begin_packages(args.reload_present != NULL)) {
        fprintf(stderr, "%s: failed to load my package.\n", progname);
        exit(1);
    }

    init_clock();

    signal(SIGCHLD, child_handler);

    clock_loop();

    death_handler(ps_wire);
}
