/* AP Radar
 * Started June 2002
 * donald.g.park@iname.com
 *
 * Released under the MIT Open Source Licence
 * http://www.opensource.org/licenses/mit-license.php
 */

using namespace std;

#include <string>
#include <gtkmm/main.h>
#include <libgen.h>                               // for dirname()
#include <unistd.h>                               // for geteuid()
#include <iostream>
#include <sys/stat.h>
#include "Config.h"
#include "Window.h"
#include "ccode.h"
#include "AccessPointList.h"
#include "Main.h"
#include "NetworkInterface.h"

AccessPointList* Main::ScanAPs()
{
    /* The list of APs */
    AccessPointList* aplist = NULL;

    if(getConfig()->getInterface() == NULL) {
        cout << "No interface has been chosen. skipping AP scan" << endl;
        aplist = new AccessPointList;
        // Use a phony AP when no interface is found
        AccessPoint* pap = new AccessPoint;
        pap->sampleValues();                      // Set sample values

        aplist->push_back(pap);                   // add to the list of APs
    }
    else if ((getConfig()->getInterface()->getName()->compare("driverloader")) == 0) {
        cout << "driverloader in use. skipping wireless scan" << endl;
    }
    else {
        // add multiple device support at some point
        cout << "Main::ScanAPs on interface " <<
            *(getConfig()->getInterface()->getName()) << endl;
        aplist = print_scanning_info(getConfig()->getSkfd(),
            getConfig()->getInterface()->getName()->c_str());

        // Test the result of print_scanning_info
        if(aplist != 0) {
            // we got something back. print out the contents
            AccessPointList::const_iterator it;
            it = aplist->begin();
            for(int i=0;it != aplist->end(); ++i,++it) {
                cout << "#" << i;
                (*it)->printValues();
            }
        }
        else {
            // print_scanning_list returns null on error
            cout << "wireless scan returned no information!" << endl;
        }
    }

    /* Close the socket. */
    return aplist;
}


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

    cout << "AP Radar " << VERSION << endl;
    // Start the configuration object
    Config config;

    if(geteuid() != 0) {
        cout << " *** AP Radar should be run as root ***" << endl;
    }

    // Find the resource directory
    char pathbuff[256];
    char testpath[256];
    strcpy(pathbuff, dirname(argv[0]));
    strcpy(testpath, pathbuff);
    strcpy(testpath+strlen(testpath),"/logo.png"  );
    struct stat statstruct;
    if(stat(testpath,  &statstruct) == 0) {
        config.setDirname(new string(pathbuff));
    }
    else {
        config.setDirname(new string("/usr/share/apradar"));
    }

    cout << "Resource directory is set to " << *(config.getDirname()) << endl;

    config.loadConfigOptions();

    NetworkInterface *nif = NULL;
    NetworkInterface *test = new NetworkInterface;
    test->setConfig(&config);
    test->getIpv4Address();

    // gtkmm command line processing
    Gtk::Main kit(argc, argv);

    // command line processing
    if(argc > 1) {
        for (int i=0; i < argc; i++) {
            //cout << "#" << i << " " << argv[i] << endl;
            if(strcmp(argv[i], "-s") == 0) {
                config.setPhantomAPs(true);
            }
            if(strcmp(argv[i], "-i") == 0) {
                nif = new NetworkInterface;
                nif->setConfig(&config);
                cout << "i is " << i << argv[i] << endl;
                i++;
                if (i >= argc) {
                    cout << "Specify an interface name with -i. current i = "<< i << endl;
                    return 1;
                }
                nif->setName(new string(argv[i]));
            }
            if(strcmp(argv[i], "-d") == 0) {
                i++;
                if (i >= argc) {
                    cout << "Specify a dhcp client command with -d " << endl;
                }
                config.setDhcpCommand(new string(argv[i]));
                cout << "custom dhcp client command set to \"" << argv[i] << "\"" << endl;
            }
            if(strcmp(argv[i], "--help") == 0 || strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "-?") == 0) {
                cout << "AP Radar command line options" << endl;
                cout << "-i <wireless interface name>" << endl;
                cout << "-d <dhcp client command> [the interface name is added at the end]" << endl;
                return 1;
            }
        }
    }

    // main is a utility class of sorts
    Main main;
    main.setConfig(&config);
    config.setMain(&main);

    // Start the GTK object
    //Gtk::Main gtkmain (argc,argv);

    // Start the Window object (inherits from GtkWindow)
    Window window;
    window.setConfig(&config);
    config.setWindow(&window);
    window.init();

    // NULL means no interface was specified on the command line
    if(nif == NULL) {
        nif = config.findInterface();
    }

    // if still null report an error
    if(nif == NULL) {
        cout << "No wireless interfaces found in /proc/net/wireless" << endl;
        cout << "** Using simulation mode" << endl;
        //return 1;
    } else {
        nif->setConfig(&config);
        window.setInterface(nif);
        config.setInterface(nif);
    }

    // Setup a new AP list
    cout << "Initializing Access Point List"<< endl;
    config.setAPs(new AccessPointList);

    AccessPointList* apl;
    // scan the current environment
    //    cout << "==Initial scan started" << endl;
    //    apl = main.ScanAPs();
    //    config.syncAPList(apl);

    //    cout << "==Initial scan finished." << endl;

    //window.show();

    //Todo: Tie in the wireless signal/callback to GTK's main loop.

    /* Enter the event loop */
    Gtk::Main::run(window);

    // should we use this instead
    // 	/* computation going on */
    // 	...
    //  while (gtk_events_pending ())
    // 	  gtk_main_iteration ();
    //  ...
    // 	/* computation continued */

    return(0);
}


/*
 * Copyright (c) 2002 Donald G. Park
 * The MIT License
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to
 * deal in the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 */
