/* -TAG:LICENSE-
   
   This file is under the DigitalSpark Freeware Class License, see the
   file LICENSE for complete licensing information.
                                                         
                                                         -TAG:LICENSE- */
#include <Threading.h>
#include "tricky.h"

extern	void 	FirstRun( void );

/* 
   Do some basic things before the threads get started up and run.
*/

int Startup( void )
{
int	i=0;
int	NewInstall=0;
char	dirbuff[1024];

initThreadingDB();

printf("---- TrickyIRC %i.%i.%i -------------------------------------------\n",VerMajor,VerMinor,VerTiny);
printf("- Copyright (c) 1997-1999 DigitalSpark.  All rights reserverd. -\n");
printf("- Created by Trolld (troll@digitalspark.net)                   -\n");
printf("-                                                              -\n");

ErrorPath[1] = stdout;

ErrorPathCount=2;
sprintf(dirbuff,"%s/.trickyirc/logs/messages",getenv("HOME"));
if ( (ErrorPath[0] = fopen(dirbuff, "a")) == NULL )
   {
   /* couldn't open the file for some reason */
   ErrorPath[0] = stdout;
   ErrorPathCount=1;
   Error(1,"Couldn't open ~/.trickyirc/logs/messages, console only logging.");
   NewInstall++;
   }

setbuf(stdout,0);
setbuf(ErrorPath[0],0);


Error(10,"Starting services");

sprintf(ConfigFilePath,"%s/.trickyirc/config",getenv("HOME"));
strcpy(IRCServer,"trickyirc");

if ( ConfigLoad(ConfigFilePath) == -1 )
   {
   Error(2,"Couldn't load ~/.trickyirc/config");
   NewInstall++;
   if ( NewInstall == 1 )
      {
      Error(0,"Read the documentation!");
      }
   if ( NewInstall == 2 )
      {
      Error(0,"It seems that this is the first time TrickyIRC has run ...");
      FirstRun();
      Error(0,"Restart TrickyIRC after you've edited ~/.trickyirc/config");
      }
   exit(1);
   }

while ( i <= 30 )
   {
   Channels[i] = NULL;
   i++;
   }
i=0;

printf("-  (-) Listening on Port: %-5i                                -\n",GetConfigInt("Arbiter.ListenPort=",0));
printf("-                                                              -\n");

if ( Detach == 1 )
   {
   ErrorPathCount=1;
   if ( daemon(-1,1) == -1 )
      printf("- ERROR: Couldn't detach from console.                         -\n");
   }


while ( i <= MAX_CLIENTS )
   {
   Client[i].State = CS_FREE;
   Client[i].Authorized = 0;
   Client[i].Mutex = PTHREAD_MUTEX_INITIALIZER;
   i++;
   }

IDString[0] = 0;

return 0;
}
