/*
Copyright 1990-2001 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.

*/

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
#include <signal.h>

#include <string.h>
#include <errno.h>
#include <syslog.h>
#include "SharedData.h"

#ifdef SunOS
#include <locale.h>

#ifdef	DELAYED_START
#include <kstat.h>
#include <sys/utsname.h>
#include <sys/sysinfo.h>
#include <locale.h>

#define HARDLIMIT 120
#define DESKTOPINTERVAL 16
#define INITINTERVAL 30
#define MININTERVAL 2

static int
is_desktop_up(){
    const char *X11unix="/tmp/.X11-unix" ; /* May be Solaris only */
    const char *X11pipe="/tmp/.X11-pipe" ; /* May be Solaris only */

    return (!access(X11unix, F_OK) || !access(X11pipe, F_OK));
}

static void
zalloc(void **p, int size, int free_first){
    if (free_first && *p != NULL)
	free(*p);
    if ((*p = (void *)malloc(size)) == NULL){
      syslog(LOG_ERR, "malloc failed");
      exit(1);
    }
    memset(*p, 0, size);
}

static int
is_load_or_cpu_low(int loadlowwater, int cpulowwater, int *newinterval){
    int interval = *newinterval ;
    static int initialized = 0 ;
    static kstat_ctl_t *kc ;
    static kstat_t *ksp ;
    static kstat_t *system_misc_ksp ;
    static kstat_t *cpu_stat_0_ksp ;
    static kstat_named_t *avenrun_1min_knp ;
    static int ncpus = 0;
    static kstat_t **cpu_stat_list = 0;
    static cpu_sysinfo_t cpu_sysinfo_all;
    static cpu_vminfo_t	cpu_vminfo_all;
    int idle, pgin ;
    static int b[10]; /* buffer */

    int i, j;
    cpu_stat_t cs;
    ulong *np, *tp;

    if(!initialized){
	initialized = 1 ;
	if ((kc = kstat_open()) == NULL){
	    syslog(LOG_WARNING, "kstat_open() fails\n");
	    return 0;
	}

	if((system_misc_ksp = kstat_lookup(kc, "unix", 0, "system_misc")) == 0){
	  syslog(LOG_NOTICE, "kstat lookup: unix, system_misc\n");
	  return 0;
	}
	if(kstat_read(kc, system_misc_ksp, NULL) == -1){
	  syslog(LOG_NOTICE, "kstat read: system_misc\n");
	  return 0;
	}
	if((avenrun_1min_knp = kstat_data_lookup(system_misc_ksp,
						 "avenrun_1min"))== 0){
	  syslog(LOG_NOTICE, "kstat lookup: unix, system_misc avenrun_1min\n");
	  return 0;
	}

	for (ksp = kc->kc_chain; ksp; ksp = ksp->ks_next)
		if (strncmp(ksp->ks_name, "cpu_stat", 8) == 0)
			ncpus++;

	zalloc((void **)&cpu_stat_list, ncpus * sizeof (kstat_t *), 1);

	ncpus = 0;
	for (ksp = kc->kc_chain; ksp; ksp = ksp->ks_next)
		if (strncmp(ksp->ks_name, "cpu_stat", 8) == 0 &&
                    kstat_read(kc, ksp, NULL) != -1)
			cpu_stat_list[ncpus++] = ksp;

	if (ncpus == 0){
	  syslog(LOG_ERR, "can't find any cpu statistics\n");
	  exit(1);
	}

#ifdef DEBUG
printf("#CPU: %d\n", ncpus);
#endif
	
    } /* end initialized */

    memset((void *)&cpu_sysinfo_all, 0, sizeof (cpu_sysinfo_all));
    memset((void *)&cpu_vminfo_all, 0, sizeof (cpu_vminfo_all));

    if(kstat_read(kc, system_misc_ksp, NULL) == -1){
      syslog(LOG_NOTICE, "kstat read: system_misc\n");
      return 0;
    }
    if((avenrun_1min_knp = kstat_data_lookup(system_misc_ksp,
					     "avenrun_1min"))== 0){
      syslog(LOG_NOTICE, "kstat lookup: unix, system_misc avenrun_1min\n");
      return 0;
    }
    b[0] = avenrun_1min_knp->value.ul ;

    for (i = 0; i < ncpus; i++) {
		if (kstat_read(kc, cpu_stat_list[i], (void *)&cs) == -1)
			return (1);
		np = (ulong *)&cpu_sysinfo_all;
		tp = (ulong *)&cs.cpu_sysinfo;
		for (j = 0; j < sizeof (cpu_sysinfo_t); j += sizeof (ulong_t))
			*np++ += *tp++;
		np = (ulong *)&cpu_vminfo_all;
		tp = (ulong *)&cs.cpu_vminfo;
		for (j = 0; j < sizeof (cpu_vminfo_t); j += sizeof (ulong_t))
			*np++ += *tp++;
	}
#ifdef DEBUG
printf("usr+nice: %3d sys %3d idle %3d pgin %d\n",
       (((cpu_sysinfo_all.cpu[CPU_USER] - b[1])*100/interval)/100)+
       (((cpu_sysinfo_all.cpu[CPU_WAIT] - b[2])*100/interval)/100),
       ((cpu_sysinfo_all.cpu[CPU_KERNEL] - b[3])*100/interval)/100,
       ((cpu_sysinfo_all.cpu[CPU_IDLE] - b[4])*100/interval)/100,
       ((cpu_vminfo_all.pgpgin - b[5])*100/interval)/100
	);
#endif
    idle = ((cpu_sysinfo_all.cpu[CPU_IDLE] - b[4])*100/interval)/100 ;
    pgin = ((cpu_vminfo_all.pgpgin - b[5])*100/interval)/100 ;

    if (idle > 25 && (idle - b[4])>10)
	*newinterval = (interval+MININTERVAL)/2 ;

    b[1] = cpu_sysinfo_all.cpu[CPU_USER];
    b[2] = cpu_sysinfo_all.cpu[CPU_WAIT] ;
    b[3] = cpu_sysinfo_all.cpu[CPU_KERNEL];
    b[4] = cpu_sysinfo_all.cpu[CPU_IDLE];
    b[5] = cpu_vminfo_all.pgpgin;

    /* why pgin? */
    if(idle > 90 /* && pgin < 20 */){
	*newinterval = 1 ;
	return 1 ;
    }
    return 0 ;
}

#endif /* DELAYED_START */
#endif /* SunOS */

static void clean_up(int);

int htt_pid=0;

int
main(argc, argv)
    int		argc;
    char	**argv;
{
    const char *httpath="/usr/lib/im/htt_server" ; /* SUNWiiimf Only */
    pid_t pgrp;
    void (*disp)(int);
    char **new_argv, **pp;
    int newargc = 1, i, retry_on_error = 4, retrycount;

#ifdef SunOS
    
#ifdef	DELAYED_START
    int hardlimit = HARDLIMIT  ; /* Experimental: 2 minutes */
#endif /* DELAYED_START */
    int interval          ;  /* Experimental: 2 sec */
    int salt = 1 ;         /* salt should reflect perf measurement */
    int loadlowwater = 1 ; /* Experimental */
    int cpulowwater = 20 ; /* 20% */
    static int desktop_is_up ;
    static int confirm = 0 ;
    int use_syslog;
    char * message_locale;

    setlocale(LC_ALL, "");

    use_syslog = 0;
    message_locale = NULL;
    /* not enough */
    for (i = argc - 1, pp = argv + 1; 0 < i; --i, pp++) {
	if (0 == strcmp(*pp, "-syslog")) {
	    use_syslog = 1;
	} else if (0 == strcmp(*pp, "-message_locale")) {
	    if (1 == i) break;
	    --i;
	    pp++;
	    message_locale = *pp;
	} else if (0 == strcmp(*pp, "-retryonerror")) {
	    if (1 == i) break;
	    --i;
	    pp++;
	    retry_on_error = atoi(*pp);
	} else if (0 == strcmp(*pp, "-h") ||
		   0 == strcmp(*pp, "-help") ||
		   0 == strcmp(*pp, "--help")) {
	    fprintf(stderr, "Usage: %s [-retryonerror NUM]\n", argv[0]);
	    exit(1);
	} else {
	    /* unknown options found. stop parsing option for htt here */
	    break;
	}
    }
    newargc = argc - i;

    openlog("htt", LOG_PID, LOG_USER);

    /* BugId : 4281734. No need to have delayed start now.
       iiim_server does not require X connection and will be started only
       in asian locales.
    */
#ifdef DELAYED_START
    if (desktop_is_up = is_desktop_up()){
	/* Must not be from bootup time */
	interval = MININTERVAL ;
    } else {
	interval = INITINTERVAL ;
    }
    
    for(; hardlimit > 0; hardlimit -= interval){ /* delayed start loop */

#ifdef DEBUG
printf("%3d | ", salt*HARDLIMIT - hardlimit);
#endif

	if (is_load_or_cpu_low(loadlowwater, cpulowwater, &interval)){
	    confirm++ ;
	} else {
	    confirm = 0 ;
	}
        if (confirm > 0)
	    break ;

        if(!desktop_is_up){
	    if (is_desktop_up()){
		desktop_is_up = 1 ; 
		/* Causes too much delay - 4264139 
		interval += DESKTOPINTERVAL ;
		*/
#ifdef DEBUG
printf("Desktop is up now\n");
#endif
	    }
	}
        if(interval > MININTERVAL){
	    interval=(interval+MININTERVAL)/2;
	}
	sleep(interval);

#ifdef DEBUG
        fflush(stdout);
#endif

    }

#endif  /* DELAYED_START */

#ifdef DEBUG
printf("Go though\n");
#endif

#else
    for (i = argc - 1, pp = argv + 1; 0 < i; --i, pp++) {
	if (0 == strcmp(*pp, "-retryonerror")) {
	    if (1 == i) break;
	    --i;
	    pp++;
	    retry_on_error = atoi(*pp);
	} else if (0 == strcmp(*pp, "-h") ||
		   0 == strcmp(*pp, "-help") ||
		   0 == strcmp(*pp, "--help")) {
	    fprintf(stderr, "Usage: %s [-retryonerror NUM]\n", argv[0]);
	    exit(1);
	} else {
	    /* unknown options found. stop parsing option for htt here */
	    break;
	}
    }
    newargc = argc - i;

    openlog("htt", LOG_PID, LOG_USER);

#endif /* SunOS */
#ifdef SunOS
    sigset(SIGTERM, clean_up);
    sigset(SIGINT, clean_up);
#else
    signal(SIGTERM, clean_up);
    signal(SIGINT, clean_up);
#endif

#ifdef SunOS
    pgrp = setsid();
    if ((pid_t)(-1) == pgrp)
      fprintf (stderr,"cannot set session id");

#else /* !SunOS */
    pgrp = setpgrp(); 
#endif /* !SunOS */

    /* Create new argv */
    new_argv = (char**) malloc(sizeof(char*) * (argc + 2));
    if (!new_argv) {
      syslog(LOG_ERR, "malloc failed");
      exit(1);
    }
    new_argv[0]="htt_server";
    new_argv[1] = "-nodaemon";
    if (argc > 0)
      memcpy(new_argv + 2, argv + newargc, sizeof(char*) * argc - newargc);
    else
      new_argv[2]= NULL;

    retrycount = retry_on_error;

    for(;;){
#ifdef DEBUG
        fflush(stdout);
#endif
	if((htt_pid = fork()) == 0){
	    /* XXX uid should be changed to nobody */
            execv(httpath, new_argv);
	    syslog(LOG_ERR, "execv htt_server failed\n");
            exit(17);
	} else if(htt_pid < 0) {
	    syslog(LOG_WARNING, "htt watchdog: fork was failed\n");
	    sleep(60);
	} else {
            int status ;
            waitpid(htt_pid, &status, 0) ;
	    
	    if (WIFSIGNALED(status)) {
		switch(WTERMSIG(status)) {
		  case SIGTERM :
		  case SIGKILL : /* there must be a reason */
		      exit (0);
		      break ;
		  case SIGCHLD :
		      kill(htt_pid, SIGTERM);
		      exit(1);	
		  case SIGSEGV:
		      syslog(LOG_WARNING, "htt watchdog: htt_server segfaulted");
		      retrycount--;
		      break;
		  case SIGABRT:
		      syslog(LOG_WARNING, "htt watchdog: htt_server aborted");
		      retrycount--;
		      break;
		  default:
		     /* 
		      * 1999/09/28
		      * SIGTERM seems more appropriate,
		      * but orphan htt_server's do not
		      * stop with SIGTERM.
		      */
#ifdef SunOS
		      disp = sigset(SIGUSR1, SIG_IGN);
		      kill(-pgrp, SIGUSR1);
		      sigset(SIGUSR1, disp);
#else /* !SunOS */
		      disp = signal(SIGUSR1, SIG_IGN);
		      kill(-pgrp, SIGUSR1);
		      signal(SIGUSR1, disp);
#endif /* !SunOS */
		      break ;
		}
		if (retrycount < 0) {
		    syslog(LOG_ERR, "give up trying to run htt_server.\n");
		    kill(htt_pid, SIGTERM);
		    exit(1);
		}
		sleep(1);
	    } else if (WIFEXITED(status)) {
		switch(WEXITSTATUS(status)) {
		  case 100: /* unknown options was given */
		      syslog(LOG_ERR, "unrecognized options was given to htt_server.\n");
		      retrycount = 0;
		  case 17 : /* failed to execv() */
		  case 255: /* seriously not continued working */
		  case NOLEIF_EXITCODE :   /* Kill the server */
		  case NORUN_EXITCODE :   /* fix for 4297357 */
		      retrycount--;
		      if (retrycount < 0) {
			  syslog(LOG_ERR, "give up trying to run htt_server.\n");
			  kill(htt_pid, SIGTERM);
			  exit(1);	
		      }
		      sleep(1);
		      break;
		  default:
		      retrycount = retry_on_error;
		      break ;
		}
	    }
	}
    }
}

void clean_up(int unused){
    kill(htt_pid, SIGTERM);
    exit(1);
}
