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

#include <iostream>
#include <fstream>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/types.h>
#include "Config.h"
#include "AccessPointList.h"

using namespace std;

Config::Config()
{
    dirname = new string("");
    interface = NULL;
    dhcpCommand = new string ("dhclient");

    /* Create a channel to the NET kernel. */
    int skfd;
    if((skfd = socket(AF_INET, SOCK_DGRAM,0) ) < 0) {
        cout << "socket creation error in Config::Config()" << endl;
    }
    setSkfd(skfd);
}


void Config::setMain(Main* m)
{
    main = m;
}


Main* Config::getMain()
{
    return main;
}


void Config::setWindow(Window* w)
{
    win = w;
}


Window* Config::getWindow()
{
    return win;
}


void Config::setSkfd(int s)
{
    skfd = s;
}


int Config::getSkfd()
{
    return skfd;
}


void Config::setInterface(NetworkInterface* iface)
{
    if(iface != NULL) {
        cout << "config: setting interface to " << *(iface->getName()) <<
            ". " << *(iface->getDriverName()) << " driver." << endl;
    }
    interface = iface;
}


NetworkInterface* Config::getInterface()
{
    return interface;
}


// return the first interface from /proc/net/wireless
NetworkInterface* Config::findInterface()
{
    NetworkInterface *ifn;
    ifn = new NetworkInterface();
    ifn->setConfig(this);

    // Pull interface names out of /proc/net/wireless
    ifstream *in;
    in = new ifstream("/proc/net/wireless");

    char line[128];
    string *s;
    string *nss;
    while (in->getline(line,127)) {
        s = new string(line);
        string::size_type colonpos;
        colonpos = s->find_first_of(':');
        if((int)colonpos > 0 ) {
            // We've got an interface
            string::size_type nospacepos;
            nospacepos = s->find_first_not_of(' ');
            // I dont know how to assign this to s, a string*
            // so i went with nss, a string
            nss = new string(s->substr(nospacepos, colonpos-nospacepos));
						cout << "ifn is " << ifn << endl;
            ifn->setName(nss);
						cout << "segfault buey" << endl;
            return ifn;
        }
        delete s;
    }
    delete in;

    return NULL;

}


void Config::setAPs(AccessPointList* apl)
{
    aplist = apl;
}


AccessPointList* Config::getAPs()
{
    return aplist;
}


void Config::syncAPList(AccessPointList* apl)
{
    // mark all the APs as 'gone away'
    // the mark any APs in apl as 'here'

    // no need to sync a non-existant list
    if (apl == NULL) return;

    // Compare the incoming list with the existing AP List
    AccessPointList::const_iterator newit;
    newit = apl->begin();
    for(;newit != apl->end(); ++newit) {
        AccessPointList::const_iterator oldit;
        oldit = aplist->begin();
        bool addme = true;
        for(;oldit != aplist->end(); ++oldit) {
            if( (**oldit) == (**newit) ) {
                // Already have this AP
                cout << "Already have AP " << *((*newit)->getBssidString()) << " " << *((*newit)->getEssid()) << endl;
                addme = false;

                // Check for updates
                if( (*oldit)->hasDifferences(*newit) == true) {
                    (*oldit)->updateValues(*newit);
                    win->refresh_AP(*oldit);
                }
            }
        }
        if(addme == true) {
            //cout << "Adding AP Essid:" << *(*newit)->getEssid() << endl;
            win->add_AP(*newit);
            aplist->push_back((*newit));
        }
    }
    cout << "SyncAPs finish.  aplist->size() " << aplist->size() << endl;
}


void Config::setPhantomAPs(bool pap)
{
    PhantomAPs = pap;
}


bool Config::getPhantomAPs()
{
    return PhantomAPs;
}


void Config::setDirname(string* dn)
{
    if(dn != 0) {
        if(dn->length() > 0) {
            dirname = dn;
            //cout << "Config::setDirname setting " << *dn << endl;
        }
        else {
            cout << "Config::setDirname given 0 length string" << endl;
        }
    }
    else {
        cout << "Config::setDirname given 0 pointer" << endl;
    }
}


string* Config::getDirname()
{
    //cout << "Config::getDirname HERE returning " << " addr:" << dirname << endl;
    //if(dirname != NULL) {
    //	cout << "value: " << *dirname << endl;
    //}
    return dirname;
}


void Config::setDhcpCommand(string* dc)
{
    dhcpCommand = dc;
}


string* Config::getDhcpCommand()
{
    return dhcpCommand;
}


void Config::setRunDhcp(bool yn)
{
    config_run_dhcp = yn;
}


bool Config::getRunDhcp()
{
    return config_run_dhcp;
}


void Config::setPingGateway(bool yn)
{
    config_ping_gateway = yn;
}


bool Config::getPingGateway()
{
    return config_ping_gateway;
}


void Config::saveConfigOptions()
{
    string homedir(getenv("HOME"));
    string options_directory = homedir + "/.apradar";
    struct stat buf;
    int retval = stat(options_directory.c_str() , &buf);
    if(retval != 0) {
        cout << "creating " << options_directory << endl;
        mkdir(options_directory.c_str(),0);
        int retval = stat(options_directory.c_str() , &buf);
        if(retval != 0) {
            cout << "error creating " << options_directory << " errno=" << errno << endl;
            return;
        }
    }

    // write user-configurable options to disk
    string options_filename = options_directory + "/options";
    cout << "Saving options to " << options_filename << endl;

    ofstream *out;
    out = new ofstream(options_filename.c_str());
    if(!out) {
        cout << "error saving to " << options_filename << endl;;
        return;
    }

    *out << "ping_gateway " << (config_ping_gateway ? "true" : "false") << endl;
    *out << "run_dhcp " << (config_run_dhcp ? "true" : "false") << endl;

    out->close();
}


void Config::loadConfigOptions()
{
    // load options from disk
    string homedir(getenv("HOME"));
    string options_filename = homedir + "/.apradar/options";
    cout << "Loading options from " << options_filename << endl;

    ifstream *in;
    in = new ifstream(options_filename.c_str());
    if(!in) {
        cout << "error loading from " << options_filename << endl;;
        return;
    }
    string f1, f2;

    while (*in >> f1 >> f2 ) {
        cout << "config read \"" << f1 << "\" \"" << f2 << "\"" << endl;
        if(f1 == "ping_gateway") {
            if(f2 == "true") {
                config_ping_gateway = true;
            }
            else if(f2 == "false") {
                config_ping_gateway = false;
            }
            else {
                cout << "bogus setting on " << f1 << " of \"" << f2 << "\"" << endl;
            }
        }

        if(f1 == "run_dhcp") {
            if(f2 == "true") {
                config_run_dhcp = true;
            }
            else if(f2 == "false") {
                config_run_dhcp = false;
            }
            else {
                cout << "bogus setting on " << f1 << " of \"" << f2 << "\"" << endl;
            }
        }
    }
}


/*
 * 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.
 */
