/*
	Schrodinger's Box Haven  code version -0.1 alpha
        Copyright (C) 1994, Gordon Chan

	You can do whatever ya want with this code as long as you leave this
        copyright & disclaimer intact.  You can hack it up all you want, etc...
        No guarantees.

	Send comments, flames, bug reports, etc ... to
		au233@freenet.carleton.ca  <---- (preferred address for now)
		gjc@achilles.net
		gchan@ccs.carleton.ca
*/


/* Here's the copyrights & disclaimers from the Opium Den and unixCB codes */

/* Opium Den */
/*
  val's haven code v -0.85

        Copyright (C) 1994 Joel Ward

        Warranty:
                Don't blame me for anything.

        You can do whatever the fuck you want with this code as long as you
don't remove this copyright/disclaimer notice.
*/

/* unixCB */
/*
  
  cbd.c
  
  "cbd.c" is the main code for the CB simulator.
  
  Copyright (c) 1992, Gary Grossman.  All rights reserved.
  Send comments and questions to: garyg@soda.berkeley.edu
  
  */

#include<stdio.h>
#include<stdlib.h>
#include<signal.h>

#include "main.h"
#include "linked_lists.h"


/* main forks out process and initilizes the server socket and goes into 
   the main loop */

void main (argv, argc)
	int argv;
	char **argc;
{
	int  childid, sock, port = DEFAULTPORT;	

	if (argv == 2) {
		port = atoi(argc[1]);
		if (!port || port < 1024) {
			printf ("bad port number\n");
			printf ("valid port numbers are >= 1024\n");
			exit (0);
		}			
	}

#ifdef DEBUG
	dup2 (2, FD_ERR);
#endif

#ifndef DEBUG
	if (childid = fork() ) {
		printf ("port = %d\n", port);
		printf ("child process id = %d\n", childid);
		printf ("parent process is tuning out\n");
		exit (0);
	}
	close_std();
#endif

	if ((sock = init_socket (port)) == -1)
		return; 

#ifdef DEBUG
	sprintf (err, "server's file descriptor is %d\r\n", sock );
	write_err (err);
	sprintf (err, "server is listening on port %d\r\n", port );
	write_err (err);
#endif

	main_loop (sock);
 
}


void close_std ()
{ 
	close (0);
	close (1);
	close (2);
}

/* signal handlers */

void do_shutdown ()
{
	struct user *u;

	for (u = firstuser; u; u = u->next) {
		if (is_user (u, Ftyping) || is_user (u, Fcomm_line) )
			write_user (u->desc, "\r\n");
		delete_user (u, ">> Shutdown.\r\n", 1);
	}
	exit (0);
}	
		

void signal_handler ()
{
	signal (SIGBUS, SIG_DFL);	
	signal (SIGPIPE, SIG_IGN);
	signal (SIGTERM, do_shutdown);	
}
