/*

Simple wget web http client program.

Author: Matthew William Coan
Date: Sun Oct 24 19:00:22 EST 2010

*/
#include <iostream>
#include <string>

#ifndef __WIN32__
#include <signal.h>
#endif

#include "tcp_stream.h"

using namespace std;
using namespace net_tools;


#define TIMEOUT_VALUE 5

void
on_SIGALRM(int sig) 
{
   exit(0);
}

string
get_domain(const string & url)
{
   string ret;

   size_t i = 7;

   while(i < url.size()) {
      if(url[i] == '/') {
         break;
      }

      ret += url[i];

      i++;
   }

   return ret;
}

string 
get_URI(const string & url)
{
   string ret;
   bool in_uri = false;

   for(size_t i = 7; i < url.size(); i++) {
      if(url[i] == '/') {
         in_uri = true;
      }

      if(in_uri) {
         ret += url[i];
      }
   }

   if(ret == "") {
      ret = "/";
   }
   
   return ret;
}

int
main(int argc,
     char ** argv,
     char ** envp)
{
#ifdef __WIN32__
WSADATA wsaData;
WSAStartup(MAKEWORD(2,2), &wsaData);
#endif
#ifndef __WIN32__
   signal(SIGALRM, on_SIGALRM);
#endif

   if(argc != 2) {
      cerr << "usage: " << argv[0] << " <URL>" << endl << flush;
      exit(1);
   }

   string url = argv[1];

   string domain = get_domain(url);

   string uri = get_URI(url);

   if(url.find("http://") == string::npos) {
      cerr << "only http:// URLs are allowed" << endl << endl;
      exit(1);
   }

   if(domain.size() && uri.size()) {
#ifndef __WIN32__
      alarm(TIMEOUT_VALUE);
#endif

      tcp_stream stream(domain.c_str(), 80);

      if(stream) {
         string request = "GET " + uri + " HTTP/1.0\r\n\r\n";

         stream << request;

         char ch = stream.get();

         while(stream) {
            cout << ch;

            ch = stream.get();
         }

         cout << flush;

         stream.close();
      }

#ifndef __WIN32__
      alarm(0);
#endif
   }

#ifdef __WIN32__
WSACleanup();
#endif

   return 0;
}

