/**************************************************

         mbot  -  mirage irc bot
         
***************************************************/

#include "mbot.h"

CBot* bot;

void
mbot_exit (void)
{
  delete bot;
  exit (0);
}

void
handler_sigterm (int)
{
  for (int i = 0; i < bot->server_num; i++)
    bot->servers[i]->irc_quit ("received SIGTERM");
  bot->write_botlog ("FATAL: received SIGTERM");
  mbot_exit ();
}

void
handler_sigsegv (int)
{
  if (fork() > 0)
    raise (SIGQUIT);		// to dump core
  fflush (NULL);
  for (int i = 0; i < bot->server_num; i++)
    bot->servers[i]->irc_quit ("received SIGSEGV");
  bot->write_botlog ("FATAL: received SIGSEGV");
  mbot_exit ();
}

void
handler_sigfpe (int)
{
  if (fork() > 0)
    raise (SIGQUIT);		// to dump core
  fflush (NULL);
  for (int i = 0; i < bot->server_num; i++)
    bot->servers[i]->irc_quit ("received SIGFPE");
  bot->write_botlog ("FATAL: received SIGFPE");
  mbot_exit ();
}

int 
main (int argc, char *argv[])
{
  cout << setiosflags (ios::right);	// just to make seen.so load
  cout << "\n  " << VERSION_STRING << "\n\n";

  random_init ();

  signal (SIGTERM, handler_sigterm);
  signal (SIGSEGV, handler_sigsegv);
  signal (SIGFPE, handler_sigfpe);
  signal (SIGHUP, SIG_IGN);
  signal (SIGPIPE, SIG_IGN);

  bot = new CBot ();

  bot->parse_cmd (argc, argv);
  bot->parse_conf ();
  bot->check_pid ();
  bot->server_info ();

  if (!bot->debug)
    {
      int i = fork ();
      if (i == -1)
        {
          cout << " error: can't fork into background\n\n";
          exit (1);
        }
      if (i != 0)
        {
          cout << " Running in background with PID " << i << ".\n\n";
          exit (0);
        }
    }

  bot->write_pid ();

  bot->work ();

}

