//===========================================================================
//  @(#) $Name: arts++-1-1-a8 $
//  @(#) $Id: artstos.cc,v 1.8 2000/10/02 17:05:13 dwm 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<stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <time.h>
#include <errno.h>
}

#include <fstream.h>
#include <string>

#include "ArtsTosTable.hh"
#include "ArtsIfIndexSelectionSet.hh"
#include "ArtsTimeIntervalSelectionSet.hh"
#include "ArtsPackageVersion.hh"

#ifndef NDEBUG
  #include "ArtsDebug.hh"
#endif

extern char *tzname[2];

static const string rcsid = "@(#) $Name: arts++-1-1-a8 $ $Id: artstos.cc,v 1.8 2000/10/02 17:05:13 dwm Exp $";
static const ArtsPackageVersion  k_artsVersion = ArtsPackageVersion(rcsid);
static ArtsTimeIntervalSelectionSet  g_timeIntervalSet;

//-------------------------------------------------------------------------
//           static void ShowTosTable(const Arts & arts)
//.........................................................................
//  
//-------------------------------------------------------------------------
static void ShowTosTable(const Arts & arts, bool sortByPkts,
                          ArtsIfIndexSelectionSet & ifIndexSet)
{
  struct tm       *localTm;
  time_t           periodTimes[2];
  struct in_addr   inAddr;
  
  vector<ArtsAttribute>::const_iterator  periodAttribute;
  vector<ArtsAttribute>::const_iterator  hostAttribute;
  vector<ArtsAttribute>::const_iterator  ifIndexAttribute;
  vector<ArtsAttribute>::const_iterator  ifDescrAttribute;
  vector<ArtsAttribute>::const_iterator  ifIpAddrAttribute;
  
  hostAttribute = arts.FindHostAttribute();
  ifIndexAttribute = arts.FindIfIndexAttribute();
  if (ifIndexSet.size() > 0) {
    if (ifIndexAttribute != arts.Attributes().end()) {
      if (! ifIndexSet.Matches(ifIndexAttribute->IfIndex())) {
        return;
      }
    }
  }

  periodAttribute = arts.FindPeriodAttribute();
  if (periodAttribute != arts.Attributes().end()) {
    if (g_timeIntervalSet.size() > 0) {
      if ((! g_timeIntervalSet.Matches(periodAttribute->Period()[0])) ||
          (! g_timeIntervalSet.Matches(periodAttribute->Period()[1]))) {
        return;
      }
    }
  }

  if (hostAttribute) {
    inAddr.s_addr = hostAttribute->Host();
    cout << "router:  " << inet_ntoa(inAddr) << endl;
  }

  if (ifIndexAttribute != arts.Attributes().end()) {
    cout << "ifIndex: " << ifIndexAttribute->IfIndex();
  }
  ifDescrAttribute = arts.FindIfDescrAttribute();
  ifIpAddrAttribute = arts.FindIfIpAddrAttribute();
  if (ifDescrAttribute != arts.Attributes().end() &&
      ifIpAddrAttribute != arts.Attributes().end()) {
    cout << " (" << ifDescrAttribute->IfDescr() << " ";
    inAddr.s_addr = ifIpAddrAttribute->IfIpAddr();
    cout << inet_ntoa(inAddr) << ")";
  }
  cout << endl;
  
  if (periodAttribute) {
    periodTimes[0] = periodAttribute->Period()[0];
    periodTimes[1] = periodAttribute->Period()[1];
    localTm = localtime(&(periodTimes[0]));
    cout << "period:  " << setfill('0')
         << setw(2) << (int)localTm->tm_mon+1 << "/"
         << setw(2) << localTm->tm_mday << "/"
         << setw(4) << localTm->tm_year + 1900 << " "
         << setw(2) << localTm->tm_hour << ":"
         << setw(2) << localTm->tm_min << ":"
         << setw(2) << localTm->tm_sec << " - ";
    localTm = localtime(&(periodTimes[1]));
    cout << setw(2) << (int)localTm->tm_mon+1 << "/"
         << setw(2) << localTm->tm_mday << "/"
         << setw(4) << localTm->tm_year + 1900 << " "
         << setw(2) << localTm->tm_hour << ":"
         << setw(2) << localTm->tm_min << ":"
         << setw(2) << localTm->tm_sec << " " << tzname[localTm->tm_isdst]
         << endl;
  }

  time_t timeInterval = periodTimes[1] - periodTimes[0];
  
  cout << setfill(' ');
  cout << setw(8)  << "TOS"
       << setw(15) << "Pkts"
       << setw(15) << "Pkts/sec"
       << setw(15) << "Bytes"
       << setw(15) << "Bits/sec"
       << endl;
  cout << setw(8)  << "--------"
       << setw(15) << "-------------"
       << setw(15) << "-------------"
       << setw(15) << "-------------"
       << setw(15) << "-------------"
       << endl;

  if (sortByPkts)
    arts.TosTableData()->SortEntriesByPkts();
  else
    arts.TosTableData()->SortEntriesByBytes();
  
  vector<ArtsTosTableEntry>::const_iterator  tosEntry;
  for (tosEntry = arts.TosTableData()->TosEntries().begin();
       tosEntry != arts.TosTableData()->TosEntries().end();
       tosEntry++) {
    cout << setw(8) << (uint16_t)tosEntry->TosNumber()
         << setw(15) << tosEntry->Pkts()
         << setw(15)
         << (uint64_t)((double)tosEntry->Pkts() / timeInterval)
         << setw(15) << tosEntry->Bytes()
         << setw(15)
         << (uint64_t)(((double)tosEntry->Bytes() * 8.0) / timeInterval)
         << endl;
  }
  cout << endl;
  
  return;
}
  
//-------------------------------------------------------------------------
//                      void Usage(const char *argv0)                      
//.........................................................................
//  
//-------------------------------------------------------------------------
void Usage(const char *argv0)
{
  cerr << "Usage: " << argv0
       << " [-v] [-n] [-p] [-i ifIndexList] [-b beginTime]" << endl
       << "       [-e endTime] file(s)" << endl;
  return;
}

//-------------------------------------------------------------------------
//                     int main(int argc, char *argv[])                    
//.........................................................................
//  
//-------------------------------------------------------------------------
int main(int argc, char *argv[])
{
  ifstream     *artsStream;
  extern char  *optarg;
  extern int    optind;
  int           optChar;
  bool          sortByPkts = false;
  ArtsIfIndexSelectionSet   ifIndexSet;
  char                     *startTimeExpression = (char *)0;
  char                     *endTimeExpression = (char *)0;

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

  while ((optChar = getopt(argc,argv,"b:e:i:npv")) != EOF) {
    switch (optChar) {
      case 'b':
        startTimeExpression = (char *)strdup(optarg);
        break;
      case 'e':
        endTimeExpression = (char *)strdup(optarg);
        break;
      case 'i':
        ifIndexSet.Load(optarg);
        break;
      case 'p':
        sortByPkts = true;
        break;
      case 'v':
        cerr << k_artsVersion.Name() << "  " << k_artsVersion.Id() << endl;
        exit(0);
        break;
      case '?':
      default:
        Usage(argv[0]);
        exit(1);
        break;
    }
  }

  if (optind >= argc) {
    Usage(argv[0]);
    exit(1);
  }
  
  if (startTimeExpression || endTimeExpression)
        g_timeIntervalSet.Load(startTimeExpression,endTimeExpression);
  
  for (int fileNum = optind; fileNum < argc; fileNum++) {
    artsStream = new ifstream(argv[fileNum]);
    if (!artsStream || !(*artsStream)) {
      cerr << "[E] unable to open input file '" << argv[fileNum] << "': "
           << strerror(errno) << endl;
      continue;
    }

    istream_iterator<ArtsTosTable>  inStreamIter(*artsStream);
    istream_iterator<ArtsTosTable>  inStreamEnd;

    for (; inStreamIter != inStreamEnd; inStreamIter++) {
      ShowTosTable(*inStreamIter,sortByPkts,ifIndexSet);
    }
    delete(artsStream);
  }

  #ifndef NDEBUG
    atexit(ShowArtsObjectsNotFreed);
  #endif
  
  exit(0);
}
