#include <stdio.h>
#include <stdlib.h>  /* for exit */
#include <time.h>
#include <dirent.h>
#include <string.h>

#include <sys/stat.h>
#include <sys/wait.h>
#include <unistd.h>


#include "global.h"
#include "custom.h"		/* for date FORMAT strings */


#include "manhat-lib/shared_util.h"
#include "manhat-lib/shared_super_util.h"
#include "manhat-lib/shared_cs_util.h"




void
start_chat_server( )
{
      char chat_dir[MAX_PATH +1];
      char port_string[10];
      char *ptr;
      
       pid_t child_pid;
       pid_t n;
      
       sprintf(port_string,"%d",MELANGE_PORT);   /* custom.h */ 
       
       chdir(CHAT_DIRECTORY);
       getcwd(chat_dir, MAX_PATH);
      
       ptr = strrchr(chat_dir,'/');
       if(ptr && !(*ptr + 1)) /* if chat_dir ends in a slash */
          strcat(chat_dir, CHAT_PROGRAM);
       else
          {
           strcat(chat_dir, "/");
           strcat(chat_dir, CHAT_PROGRAM);
           }   
       if((child_pid = fork()) < 0)
	       cs_critical_error (ERR_CANT_START_NEW_PROCESS, "");
       if(child_pid == 0)
       { 
	       execl(chat_dir, "melange", "-q", "-p", port_string,  (char*)0);   /* -q starts chat quietly - no output! */
       }
       
         waitpid(-1, &n, WNOHANG);       /* don't wait for child to finish */

}
	 





	 
int
main ()
{
        SESSION user;
	char key[MAX_KEY + 1];

	cs_cgi_init();
	 read_param( key);
         validate_super_key(key, &user);
	 start_chat_server( key);
         cs_set_int_value("port", MELANGE_PORT);
         cs_cgi_display("super_chat_start", 1);
         cs_cgi_destroy(); 
	 
	 return 0;
}

