/* tmsql.cc
****************************************************************************************************************
****************************************************************************************************************

    Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2021 Askar Almatov

    This file is part of Trafficmeter.

    Trafficmeter is free software: you can redistribute it and/or modify it under the terms of the GNU General
    Public License as published by the Free Software Foundation, either version 3 of the License, or (at your
    option) any later version.

    Trafficmeter is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the
    implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public
    License for more details.

    You should have received a copy of the GNU General Public License along with Trafficmeter. If not, see
    <http://www.gnu.org/licenses/>.
*/

#include <cstdlib>
#include <cstring>
#include <fstream>
#include <iostream>
#include <getopt.h>
#include <unistd.h>

#include "path.h"
#include "sqlexport.h"
#include "statquery.h"
#include "tmdefs.h"

using namespace iclass;
using namespace trafficmeter;

using std::cerr;
using std::cout;
using std::flush;
using std::ofstream;
using std::string;

static const struct option  LONG_OPTIONS_[] =
{
    { "date",     required_argument, nullptr, 'd' },
    { "sender",   required_argument, nullptr, 's' },
    { "print",    required_argument, nullptr, 'p' },
    { "version",  no_argument,       nullptr, 'v' },
    { "help",     no_argument,       nullptr, 'h' },
    { nullptr,    0,                 nullptr,  0  }
};

/**************************************************************************************************************/
string
getHostname()
{
    char    fqdn[ 255 ];
    char*   s = fqdn;

    gethostname( fqdn, sizeof(fqdn) );
    return strsep( &s, "." );
}

/**************************************************************************************************************/
int
main( int argc, char* argv[] )
{
    string      progName( Path(argv[0]).fileName() );
    ltimet      now( time(nullptr) );
    periodt     timeInterval( now, now.lhour()? periodt::PLDAY : periodt::PLDAYBEFORE );
    string      sender( getHostname() );
    ofstream    sqlOutput;
    int         opt;

    while ( (opt = getopt_long(argc,argv,"d:s:p:vh",LONG_OPTIONS_,nullptr)) != -1 )
    {
        string  dieMessage;

        switch ( opt )
        {
            case 'd':

                timeInterval = periodt( ltimet(optarg,&dieMessage), periodt::PLDAY );

                if ( !dieMessage.empty() )
                {
                    cerr << progName << ": incorrect date: " << dieMessage << "\n";
                    return EXIT_FAILURE;
                }

                break;

            case 's':

                sender = optarg;
                break;

            case 'p':

                sqlOutput.open( optarg );

                if ( !sqlOutput )
                {
                    cerr << progName << ": file open error: " << optarg << "\n";
                    return EXIT_FAILURE;
                }

                break;

            case 'v':

                cout <<
                    "Trafficmeter SQL export version " << VERSION << " for " << SYSTEM_TYPE << "\n"
                    "For info, please visit http://www.trafficmeter.org\n";

                return EXIT_SUCCESS;

            case 'h':
            default:

                cout <<
                    progName << " is the utility for export required IP statistics to PostgreSQL database\n"
                    "Usage: " << progName << " [options]\n"
                    "\t-d --date=<date>\tDate in ISO-8601 format, default today or yesterday\n"
                    "\t-s --sender=<host>\tUse sender <host> to specify IP addresses, default this host\n"
                    "\t-p --print=<file>\tPrint SQL query to the <file> without execution\n"
                    "\t-v --version\t\tPrint version information\n"
                    "\t-h --help\t\tPrint help message\n";

                return EXIT_SUCCESS;
        }
    }

    SqlExport   sql( timeInterval, sender );

    if ( !sql.isConnected() )
    {
        cerr << progName << ": cannot connect to database\n";
        return EXIT_FAILURE;
    }

    if ( sql.networks().empty() )
    {
        cerr << progName << ": no IP-addresses to fetch: sender='" << sender << "'\n";
        return EXIT_SUCCESS;
    }

    cout << now.str() << " -- [" << sql.begin().str() << "; " << sql.end().str() << ") " << flush;
    sql.fetch();

    if ( sqlOutput.is_open() )
    {
        sql.print( sqlOutput );
        cout << "PRINTED\n";
        return EXIT_SUCCESS;
    }

    long    nTuples = sql.execute();

    if ( nTuples < 0 )
    {
        cout << "FAIL\n";
        return EXIT_FAILURE;
    }

    cout << nTuples << " OK\n";
    return EXIT_SUCCESS;
}
