//===========================================================================
//  @(#) $Name: arts++-1-1-a12 $
//  @(#) $Id: artsportagg.cc,v 1.2 2004/04/21 23:51:23 kkeys Exp $
//===========================================================================
//  Copyright Notice
//
//  By accessing this software, arts++, you are duly informed
//  of and agree to be bound by the conditions described below in this
//  notice:
//
//  This software product, arts++, is developed by Daniel W. McRobb, and
//  copyrighted(C) 1998 by the University of California, San Diego
//  (UCSD), with all rights reserved.  UCSD administers the CAIDA grant,
//  NCR-9711092, under which part of this code was developed.
//
//  There is no charge for arts++ software.  You can redistribute it
//  and/or modify it under the terms of the GNU Lesser General Public
//  License, Version 2.1, February 1999, which is incorporated by
//  reference herein.
//
//  arts++ is distributed WITHOUT ANY WARRANTY, IMPLIED OR EXPRESS, OF
//  MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE or that the use
//  of it will not infringe on any third party's intellectual
//  property rights.
//
//  You should have received a copy of the GNU Lesser General Public
//  License along with arts++.  Copies can also be obtained from:
//
//    http://www.gnu.org/copyleft/lesser.html
//
//  or by writing to:
//
//  Free Software Foundation, Inc.
//  59 Temple Place, Suite 330
//  Boston, MA 02111-1307
//  USA
//
//  Or contact:
//
//    info@caida.org
//===========================================================================

extern "C" {
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <time.h>
#include <errno.h>
#include "artslocal.h"
}

#ifdef HAVE_FSTREAM
  #include <fstream>
#else
  #include <fstream.h>
#endif
#include <string>

#include "ArtsPortTableAggregator.hh"
#include "Arts.hh"
#include "ArtsPortTableAggregatorMapKey.hh"
#ifndef NDEBUG
  #include "ArtsDebug.hh"
#endif

extern char *tzname[2];
extern int   errno;

using namespace std;

const string rcsid = "@(#) $Name: arts++-1-1-a12 $ $Id: artsportagg.cc,v 1.2 2004/04/21 23:51:23 kkeys Exp $";

map<ArtsPortTableAggregatorMapKey,ArtsPortTableAggregator *,less<ArtsPortTableAggregatorMapKey> >  g_portAggregatorMap;

//-------------------------------------------------------------------------
//                      void Usage(const char *argv0)                      
//.........................................................................
//  
//-------------------------------------------------------------------------
void Usage(const char *argv0)
{
  cerr << "Usage: " << argv0 << " [-q] [-o] [-h hours] outfile infile(s)"
       << endl;
  return;
}

//-------------------------------------------------------------------------
//                     int main(int argc, char *argv[])                    
//.........................................................................
//  
//-------------------------------------------------------------------------
int main(int argc, char *argv[])
{
  Arts        *arts;
  ArtsHeader   artsHeader;
  ifstream    *artsStream;
  ofstream    *out;
  extern char *optarg;
  extern int   optind;
  int          optChar;
  float        hours = -1.0;
  time_t       intervalStart = 0;
  bool         overwrite = false;
  bool         verbose = true;
  vector<ArtsAttribute>::const_iterator   periodAttribute;
  vector<ArtsAttribute>::const_iterator   hostAttribute;
  vector<ArtsAttribute>::const_iterator   ifIndexAttribute;
  ArtsPortTableAggregatorMapKey           portKey;

  map<ArtsPortTableAggregatorMapKey,ArtsPortTableAggregator *,less<ArtsPortTableAggregatorMapKey> >::iterator  portAggIter;

  if (argc < 3) {
    Usage(argv[0]);
    exit(1);
  }

  while ((optChar = getopt(argc,argv,"h:qo")) != EOF) {
    switch (optChar) {
      case 'h':
        hours = atof(optarg);
        break;
      case 'q':
        verbose = false;
        break;
      case 'o':
        overwrite = true;
        break;
      default:
        break;
    }
  }

  if (overwrite)
    out = new ofstream(argv[optind],ios::out|ios::trunc);
  else
    out = new ofstream(argv[optind],ios::out|ios::app);

  if (!out || !(*out)) {
    cerr << "unable to open '" << argv[optind] << "' as output file: "
         << strerror(errno) << endl;
    Usage(argv[0]);
    exit(1);
  }

  optind++;
  
  streampos  streamPosition;
  ArtsPortTable  *portTable = (ArtsPortTable *)NULL;
  
  for (int fileNum = optind; fileNum < argc; fileNum++) {
    artsStream = new ifstream(argv[fileNum]);
    if (! artsStream) {
      cerr << "failed to open '" << argv[fileNum] << "': "
           << strerror(errno) << endl;
      continue;
    }
    while (*artsStream) {
      //  save our stream position, we might want to back up
      //  and read a whole ARTS object.
      streamPosition = artsStream->tellg();
      //  Read the object header from the stream.  We'll use it to
      //  determine whether or not the object is a port table
      //  object.
      artsHeader.read(*artsStream);
      
      if (artsHeader.Identifier() != artsC_OBJECT_PORT) {
        //  Not a port table object, skip over it.
        artsStream->seekg(artsHeader.AttrLength() + artsHeader.DataLength(),
                          ios::cur);
      }
      else {
        //  It's a port table object.  Back up to start of header
        //  and read the whole object.
        artsStream->seekg(streamPosition,ios::beg);
        arts = new Arts();
        assert(arts != (Arts *)0);
        arts->read(*artsStream);
        if (verbose) {
          cout << ".";
          cout.flush();
        }
        periodAttribute = arts->FindPeriodAttribute();
        if (intervalStart == 0) {
          intervalStart = ((*periodAttribute).Period())[0];
        }
        
        hostAttribute = arts->FindHostAttribute();
        if (hostAttribute != arts->Attributes().end()) {
          portKey.Router(hostAttribute->Host());
        }
        else {
          portKey.Router(0);
        }

        ifIndexAttribute = arts->FindIfIndexAttribute();
        if (ifIndexAttribute != arts->Attributes().end()) {
          portKey.IfIndex(ifIndexAttribute->IfIndex());
        }
        else {
          portKey.IfIndex(0);
        }

        if (g_portAggregatorMap.find(portKey) == g_portAggregatorMap.end()) {
          g_portAggregatorMap[portKey] = new ArtsPortTableAggregator(*arts);
        }
        else {
          (g_portAggregatorMap[portKey])->Add(*arts);
        }

        delete(arts);

        if (hours > 0.0) {
          if ((periodAttribute->Period())[1] >
              (intervalStart + hours * 60 * 60)) {
            for (portAggIter = g_portAggregatorMap.begin();
                 portAggIter != g_portAggregatorMap.end(); portAggIter++) {
              portTable =
                ((*portAggIter).second)->ConvertToArtsPortTable();
              portTable->write(*out);
              delete(portTable);
              portTable = (ArtsPortTable *)NULL;
              intervalStart = 0;
              if (verbose) {
                cout << "+";
                cout.flush();
              }
            }
            g_portAggregatorMap.erase(g_portAggregatorMap.begin(),
                                      g_portAggregatorMap.end());
          }
        }
      }
    }
    artsStream->close();
  }

  if (g_portAggregatorMap.size() > 0) {
    for (portAggIter = g_portAggregatorMap.begin();
         portAggIter != g_portAggregatorMap.end(); portAggIter++) {
      portTable =
        ((*portAggIter).second)->ConvertToArtsPortTable();
      portTable->write(*out);
      delete(portTable);
      portTable = (ArtsPortTable *)NULL;
      if (verbose) {
        cout << "+";
        cout.flush();
      }
    }
    g_portAggregatorMap.erase(g_portAggregatorMap.begin(),
                              g_portAggregatorMap.end());
  }

  if (verbose) {
    cout << endl;
  }
  
  out->close();
  delete(out);
  
  #ifndef NDEBUG
    atexit(ShowArtsObjectsNotFreed);
  #endif

  exit(0);
}
