/*
 * A client for term.
 */
#define I_SYS
#define I_IOCTL
#include "includes.h"
#include "client.h"
#include <signal.h>

int debug = 0; 
int term_client_number = -1;

char * pathtail(char*);
#ifdef USE_SIGWINCH
void resizer(int foo)
{
  struct winsize ws;
  int s;
  if (ioctl(0, TIOCGWINSZ, &ws) >= 0)
    {
      s = connect_server(term_server);
      if (!s)
	/* cannot resize for some reason */
	return;
      send_command(s, C_RESIZE, 0, "%d %d %d", term_client_number,
		   ws.ws_row, ws.ws_col);
      close(s);
    }
  signal(SIGWINCH, resizer);
}
#endif

void main(int argc, char *argv[]) {
  int s, first;
  char * f;
  

  priority = 2;
  
  first = client_options(argc,argv,"",NULL);
  
  s = connect_server(term_server);
  if (s < 0 )
    exit(1);
  if (send_command(s, C_STATS, 1, "%d", -6)<0) {
    fprintf(stderr, "FATAL:Failed to get client number.\n");
    fprintf(stderr, "Reason given: %s\n", command_result);
    exit(1);
  }
#ifdef USE_SIGWINCH
  term_client_number = atoi(command_result);
  if (term_client_number < 0)
    fprintf(stderr, "Can't get client number: SIGWINCH not supported.\n");
#endif

  if (send_command(s, C_PTYEXEC, 0, "%s", f = build_arg(&argv[first]))< 0) {
    fprintf(stderr, "FATAL:Failed to exec remote command\n");
    fprintf(stderr, "Reason given: %s\n", command_result);
    exit(1);
  }
  free(f);
  send_command(s, C_DUMB, 1, 0);

#ifdef USE_SIGWINCH  
  resizer(0);
#endif

  terminal_save(1);
  terminal_raw(1);
  terminal_raw(0);
  set_nonblock(0);
  set_nonblock(1);
  set_nonblock(s);

  do_select_loop(s, 0, 1);
  
  set_block(0);
  set_block(s);

  terminal_restore(1);
  terminal_restore(0);

}


/* my function.
 * char * pathtail( char * path )
 * takes a path and returns a pointer to the last element in it
 * assumes path separator is '/'
 * assumes '\0' terminated path.
 *
 * note: returns a pointer to the string that was input. 
 * note: returns NULL if path == NULL.
 * 
 *
 * by croutons. 29 Nov 1992
 */

char * pathtail(char * p)
{
	int i;

	if ( ! p ) { 
		return NULL;
	}

	for (i = 0; p[i] != '\0'; i++); 
	for (i--; i >= 0 && p[i] != '/'; i--);
	return &p[i+1];
}
