#define I_ERRNO
#define I_SYS
#define I_SOCKET
#define I_SIGNAL
#include "includes.h"

#include "client.h"

#define MAXREDIR 32
/* improved version - does multiple redirs  -ot */

int display_num = 9;
int term_debug = 0;

char *remote_port[MAXREDIR];

int rd_connect_server(int n) {
  int s;
  
  if ((s = connect_server(term_server)) <0) {
    perror("Couldn't open term");
    close(s);
    return -1;
  }

  if (send_command(s, C_PORT, 0, "%s", remote_port[n])< 0) {
    return -1;
  }

  send_command(s, C_DUMB, 1, 0);
  return s;
}

void check_usage(int n) {
  if ( n < 2 )
    {
      fprintf ( stderr, "Usage: redir [options] {<localport> <[host:]remoteport>}\n" );
      exit(1);
    }
}

void main(int argc, char *argv[]) {
  int s;
  int first, i;
  int svs[MAXREDIR];
  signal(SIGPIPE, SIG_IGN);
  first = client_options(argc, argv,"",NULL);
  setbuf(stderr, 0);
	check_usage(argc-first);

	for (i = 0; i < MAXREDIR && first < argc;first += 2) {
		check_usage(argc - first);
		fprintf(stderr, "Redirecting %s to %s\n", argv[first], argv[first+1] );
    remote_port[i] = argv[first+1];
    
    /* Bind the local socket we are going */
    /* to listen on.  */
    s = bind_tcp(atoi(argv[first]));
    if (s == -2) {
      fprintf(stderr, "Port is already bound.\n");
    } else if (s < 0) {
      fprintf(stderr, "Can't bind to requested address. s = %d\n", s);
    } else {
      svs[i++] = s;
    }
  };
  if(!i){
    fprintf(stderr,"Nothing to do.\n");
    exit(1);
  };
  do_connect(i, svs, rd_connect_server);
}
