/*
 *  Copyright (C) 1999 AT&T Laboratories Cambridge.  All Rights Reserved.
 *
 *  This 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 software 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 software; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,
 *  USA.
 */

/*
 * listen.c - listen for incoming connections
 */

#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/time.h>
#include <sys/utsname.h>
#include <time.h>
#include <vncviewer.h>

#define FLASHWIDTH 50	/* pixels */
#define FLASHDELAY 1	/* seconds */

Bool listenSpecified = False;
int listenPort = 0, flashPort = 0;

static Font flashFont;

static void getFlashFont(Display *d);
//static void flashDisplay(Display *d, char *user);
static Bool AllXEventsPredicate(Display *d, XEvent *ev, char *arg);

static char *displayname;
static void listensockReadyCallback(gpointer clientData, gint fd, GdkInputCondition condition);
extern GtkWidget *main_window;
    
void
doListen()
{
  int i;
  XEvent ev;
  Display *d = XOpenDisplay(displayname);
  int lock_start_time;

  gtk_widget_show(main_window);
  
  printf("name=%s\n",server_CB.server_ID);
  printf("port=%d\n", ntohs(server_CB.server_port));
  if ((server_CB.lsndsp = ConnectAdv ()) > 0) {
    server_CB.g_lsndsp = gdk_input_add_priority (server_CB.lsndsp, GDK_INPUT_READ, \
					(GdkInputFunction)listensockReadyCallback, NULL, INPUT_PRIORITY);
    printf("gdksock=%d\n",(int)server_CB.g_lsndsp);
  } else {
    printf("gdksockerror\n");
  }
  for (i = 0; i < MAXCLIENT; i++)
    server_CB.cast_src[i] = EMPTY;
  
  /* discard any X events */
  while( XCheckIfEvent( d, &ev, AllXEventsPredicate, NULL ));

  lock_start_time = time(NULL);
  while( True ){
    gtk_main_iteration();
    /*************************************/
    /* 1. Control or VNC session create  */
    /* 2. Control socket receive         */
    /* 3. VNC socket receive             */
    /* 4. X Event comes                  */
    /*************************************/

    if ((server_CB.user_num != 0) && ((time(NULL) - lock_start_time) > LOCKTIME/2)) {
      CheckLockClient();
      lock_start_time = time(NULL);
    }
  }
}

void
listensockReadyCallback (gpointer clientData, gint fd, GdkInputCondition condition)
{
  struct sockaddr_in client_addr;
  int addrlen = sizeof(client_addr);
  int cnum;
  int tmpdsp;
  printf("listensockReadyCallback\n");
  printf("gint fd=%d\n",fd);
  
  /* remove listen socket */
  //gdk_input_remove(server_CB.g_lsndsp);

  /* add control socket */
  tmpdsp = accept(server_CB.lsndsp, (struct sockaddr*)&client_addr, (socklen_t *)&addrlen);
  if (tmpdsp == -1) {
    printf("listensockReadyCallback : accept error.\n");
    exit(1);
  }

  /* CTL接続済みのクライアント検索 */
  for (cnum = 0; cnum < MAXCLIENT; cnum++) {
    if (server_CB.client_grp[cnum] == NULL) continue;
    if (memcmp(&server_CB.client_grp[cnum]->client_ip, &client_addr.sin_addr, sizeof(CARD32)) == 0) {
      if ((server_CB.client_grp[cnum]->vncdsp == 0) && (server_CB.client_grp[cnum]->ctldsp != 0)) {
        /* ctl connection only */
        break;
      } else if ((server_CB.client_grp[cnum]->vncdsp != 0) && (server_CB.client_grp[cnum]->ctldsp != 0)){
        /* Already connect */
	char dummybuf[MAXBUF];
	while (read(tmpdsp, dummybuf, MAXBUF) == MAXBUF);
	close(tmpdsp);
	//server_CB.g_lsndsp = gdk_input_add_priority (server_CB.lsndsp, GDK_INPUT_READ, \
	    				    (GdkInputFunction)listensockReadyCallback, NULL, INPUT_PRIORITY);
	return;
      }
    }
  }
      
  
  /* 新規接続 */
  if (cnum == MAXCLIENT) {
    for (cnum = 0; cnum < MAXCLIENT; cnum++) {
      if (server_CB.client_grp[cnum] == NULL) {
        printf("client(cnum)=%d\n",cnum);
        break;
      }
    }
  }

  if (cnum >= MAXCLIENT) {
    printf("Access client too many.\n");
    server_CB.g_lsndsp = gdk_input_add_priority (server_CB.lsndsp, GDK_INPUT_READ, \
					(GdkInputFunction)listensockReadyCallback, NULL, INPUT_PRIORITY);
    return;
  }
  
  if (server_CB.client_grp[cnum] == NULL) {
    ConnectCTL(client_addr, tmpdsp, cnum);
    /* increment user number */
    server_CB.user_num++;
  } else if ((server_CB.client_grp[cnum]->vncdsp == 0) && (server_CB.client_grp[cnum]->ctldsp != 0)) {
    ConnectVNC(client_addr, tmpdsp, cnum);
    if ((exDB_flag) && (!chStateDB(cnum, 1))) {
      fprintf(stderr, "Can't Connect DB Server.\n");
    }
    /* 描画されないクライアントはVNCコネクション切断 */
    if (!GETSEND(cnum)) {
      if ((page != current_page) || (da_num >= draw_info[page].row * draw_info[page].column)) {
        CutVNC(cnum);
        SendVncMsg(cnum);
      }
    }
  }

  /* add listen socket */
  //server_CB.g_lsndsp = gdk_input_add_priority (server_CB.lsndsp, GDK_INPUT_READ, \
  //					(GdkInputFunction)listensockReadyCallback, NULL, INPUT_PRIORITY);

  return;
} 


/*
 * listenForIncomingConnections() - listen for incoming connections from
 * servers, and fork a new process to deal with each connection.  We must do
 * all this before invoking any Xt functions - this is because Xt doesn't
 * cope with forking very well.
 */

void
listenForIncomingConnections(int *argc, char **argv, int listenArgIndex)
{
  Display *d;
  int listenSocket, flashSocket;
  int i;
  displayname = NULL;

  listenSpecified = True;

  for (i = 1; i < *argc; i++) {
    if (strcmp(argv[i], "-display") == 0 && i+1 < *argc) {
      displayname = argv[i+1];
    }
  }

  if (listenArgIndex+1 < *argc && argv[listenArgIndex+1][0] >= '0' &&
					    argv[listenArgIndex+1][0] <= '9') {

    listenPort = LISTEN_PORT_OFFSET + atoi(argv[listenArgIndex+1]);
    flashPort = FLASH_PORT_OFFSET + atoi(argv[listenArgIndex+1]);
    removeArgs(argc, argv, listenArgIndex, 2);

  } else {

    char *display;
    char *colonPos;
    struct utsname hostinfo;

    removeArgs(argc, argv, listenArgIndex, 1);

    display = XDisplayName(displayname);
    colonPos = strchr(display, ':');

    uname(&hostinfo);

    if (colonPos && ((colonPos == display) ||
		     (strncmp(hostinfo.nodename, display,
			      strlen(hostinfo.nodename)) == 0))) {

      listenPort = LISTEN_PORT_OFFSET + atoi(colonPos+1);
      flashPort = FLASH_PORT_OFFSET + atoi(colonPos+1);

    } else {
      fprintf(stderr,"%s: cannot work out which display number to "
	      "listen on.\n", programName);
      fprintf(stderr,"Please specify explicitly with -listen <num>\n");
      exit(1);
    }
  }

  if (!(d = XOpenDisplay(displayname))) {
    fprintf(stderr,"%s: unable to open display %s\n",
	    programName, XDisplayName(displayname));
    exit(1);
  }

  getFlashFont(d);

  listenSocket = ListenAtTcpPort(listenPort);
  flashSocket = ListenAtTcpPort(flashPort);

  if ((listenSocket < 0) || (flashSocket < 0)) exit(1);

  fprintf(stderr,"%s -listen: Listening on port %d (flash port %d)\n",
	  programName,listenPort,flashPort);
  fprintf(stderr,"%s -listen: Command line errors are not reported until "
	  "a connection comes in.\n", programName);
}


/*
 * getFlashFont
 */

static void
getFlashFont(Display *d)
{
  char fontName[256];
  char **fontNames;
  int nFontNames;

//  sprintf(fontName,"-*-courier-bold-r-*-*-%d-*-*-*-*-*-iso8859-1",
  sprintf(fontName,"-*-*-bold-r-*-*-%d-*-*-*-*-*-iso8859-1",
	  FLASHWIDTH);
  fontNames = XListFonts(d, fontName, 1, &nFontNames);
  if (nFontNames == 1) {
    XFreeFontNames(fontNames);
  } else {
    sprintf(fontName,"fixed");
  }
  flashFont = XLoadFont(d, fontName);
}

/*
 * AllXEventsPredicate is needed to make XCheckIfEvent return all events.
 */

static Bool
AllXEventsPredicate(Display *d, XEvent *ev, char *arg)
{
  return True;
}
