/*
 * main.c -- The main file
 *
 * Copyright (C) 2003   Rodolfo Giometti <giometti@linux.com>
 *
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation; either version 2 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program; if not, write to the Free Software
 *   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */


#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <netdb.h>
#include <sys/socket.h>
#include <sys/select.h>

#include "c6term.h"
#include "c6stp.h"

/* --- Global variables ----------------------------------------------------- */

int status;
char user[16+1] = "";	/* nobody */
char passwd[16+1] = "";	/* none */
char mode = '\0';	/* none */
char tonick[16+1] = ""; /* nobody */

char *host;
int port;
int sock = -1;   /* to avoid close() in reset_status() can do a mess! */

char server_key[8];
char reordered_key[8];

/* --- Local functions ------------------------------------------------------ */

#define max(a, b) ((a) > (b) ? (a) : (b))

/* --- Main ----------------------------------------------------------------- */

int main(int argc, char *argv[])
{
   fd_set fdset;

   /* Force line buffer for stdin, stdout and stderr */
   setlinebuf(stdin);
   setlinebuf(stdout);
   setlinebuf(stderr);

   reset_status();

   /* Some info data */
   PINFO("C6term(inal)  - version " C6TERM_VERSION);
   PINFO("Copyright (C) - Rodolfo Giometti <giometti@linux.it>");
   PINFO("This software is covered by the GNU GPL license version 2");

   /* Ok, now the main loop */
   while (1) {
      PDEBUG("status: %d", status);
      PDEBUG("nick: %s", tonick);

      FD_ZERO(&fdset);
      FD_SET(STDIN_FILENO, &fdset);
      if (status != OFFLINE)
         FD_SET(sock, &fdset);

      if (status != STEP2 && status != DO_PONG) {
         if (select(max(STDIN_FILENO, sock)+1, &fdset, NULL, NULL, NULL) < 0) {
            MESSAGE(CANNOT_READ_COMMANDS);
            PDEBUG("select: %m");
            exit(EXIT_FAILURE);
         }
      }   /* in this case we need force "login" command */
      else
         FD_CLR(sock, &fdset);

      /* Decode the command source */
      if (FD_ISSET(STDIN_FILENO, &fdset)) {
         PDEBUG("local command received");
         manage_user_command();
      } else if (FD_ISSET(sock, &fdset)) {
         PDEBUG("remote packet server received");
         manage_server_command();
      } else {
         MESSAGE(CANNOT_READ_COMMANDS);
         exit(EXIT_FAILURE);
      }
   }

   return 0;
}

