#include <mecha.h>

int request(const char *uri, const char *hostname, const char *port, const char *host_tuple) {
  int sd;
  netTconn *conn;
  netTreader *reader;
  char buf[1024];

  logFmsg(3,"Connecting to %s:%s for %s", hostname, port, uri);


  sd=netFtcp_connect(hostname,atoi(port));

  if(sd<0) {
    logFmsg(2,"Connect failed: e: %d", errno);
    return -1;
  }

  conn=netFconn_make(sd);

  assert(conn!=NULL);

  if(host_tuple!=NULL) {
    netFconn_writef(conn,"GET %s HTTP/1.0\r\nHost: %s\r\nUser-agent: Continuity httpclient\r\n\r\n",
    uri, host_tuple);
  } else {
    netFconn_writef(conn,"GET %s HTTP/1.0\r\nUser-agent: Continuity httpclient\r\n\r\n",
    uri);
  }
  reader=netFreader_init();

  assert(reader!=NULL);

  while(netFconn_read(conn,reader,buf,sizeof(buf))>0) {
    printf("%s", buf);
  }
  fflush(stdout);

  netFreader_free(reader);  
  netFconn_close(conn); 
  netFconn_free(conn); 
}

int main(int argc, char **argv) {

  mecha_init();

  logFmsg(0,"httpclient v1.00");
  logFmsg(0,"Copyright (c) 2004, Alex Leigh");

  extern char *optarg;
  int ret;
  int u=0, p=0, s=0, h=0;
  char *u_arg=NULL, *p_arg=NULL, *s_arg=NULL, *h_arg=NULL;
  int err=0;

  while((ret=getopt(argc, argv, "u:p:s:h:"))!=EOF) {
      switch(ret) {
          case 'u':
              if(u==1) {
                  err++;
              } else {
                  u++;
              }
              u_arg=optarg;
              break;
          case 'p':
              if(p==1) {
                  err++;
              } else {
                  p++;
              }
              p_arg=optarg;
              break;
          case 's':
              if(s==1) {
                  err++;
              } else {
                  s++;
              }
              s_arg=optarg;
              break;
          case 'h':
              if(h==1) {
                  err++;
              } else {
                  h++;
              }
              h_arg=optarg;
              break;
          default:
              err++;
      }
  }

  if(s==0 || p==0 || u==0) {
      err++;
  }

  if(s_arg==NULL || p_arg==NULL || u_arg==NULL) {
      err++;
  }
  
  if(err>0) {
      printf("Usage: httpclient -s server -p port -u uri [-h http_host]\n");
      exit(0);
  }

  request(u_arg, s_arg, p_arg, h_arg);

  exit(0);
}



