/***************************************************************************
 *   Copyright (C) 2005 by Paulo Ferreira                                  *
 *   acfpaulo@gmail.com                                                    *
 *                                                                         *
 *   This program 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 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program 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 this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/

#include "filemanager.h"

#include <qdir.h>
#include <qfile.h>
#include <qlabel.h>
#include <qmessagebox.h>
#include <stdlib.h>

//-----------------------------------------------------------------------------------------------------------
//---------------- Constructor (Construct This Object) ------------------------------------------------------
//-----------------------------------------------------------------------------------------------------------
FileManager::FileManager( Languages &langs, QWidget *parent, const char *name ) : 
QWidget( parent, name ),
configData("wlan0", PEAP, MSCHAPV2, "e-U", "User@ipt.pt", "password", WEP1, TRUE, DHCPCD),
xsupplicant("wlan0"),
isSubMethod(FALSE)
{
    
    lang = new Languages( langs );
    
    //--Temp Directory Initialization-------
    QString aux( getenv("HOME") );
    aux += "/.open1xsupplicant/";     
    dir = aux;
    
    QDir directory(dir);
    if (!directory.exists())
    {        
        QDir directory_aux;
        if ( !directory_aux.mkdir( dir, TRUE ) )
            showMessage( lang->showMessage( MESSAGES, 0 ), ERROR );
        else
            lang->creatDefaultLang();
    }
                 
    createReadmeFile();

    mainGrid = new QGridLayout( this, 3, 6, 4, 4 );
    
    setupTabWidget();
    setupListView();    
    setupInfoWidget();    
            
    aux += "open1xsupplicant.conf";
    loadFile( aux );
    
    mainGrid->setRowStretch( 0, 0 );
    mainGrid->setRowStretch( 1, 0 );    
    mainGrid->setRowStretch( 2, 0 );    
    
    xsupplicant.setInterface( configData.getInterface() );
    infoDHCP_Xsupp();
    getNetworksSSID();
}

//-----------------------------------------------------------------------------------------------------------
//---------------- Destructor is Empty ----------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------------------
FileManager::~FileManager()
{
}

//-----------------------------------------------------------------------------------------------------------
//---------------- Parser to Write the Config Files ---------------------------------------------------------
//-----------------------------------------------------------------------------------------------------------
void FileManager::saveFile( const QString &filename )
{
    if ( !listView->firstChild() )
        return;

    QFile file( filename );
    if ( !file.open( IO_WriteOnly ) )
        return;

    createDHCPFile(configData.getInterface());    

    QTextStream stream( &file );
    stream.setEncoding(QTextStream::UnicodeUTF8);

    QListViewItemIterator items( listView ); 
    
    stream << "#Config file created by Open1xSupplicant software.\n#Do not change this file manually, if ";
    stream << "you dont want crash the Xsupplicant or Open1xSupplicant applications.\n\n";
    
    writeWEPSize(stream);      
        
    switch( configData.getMethod() )
    {
        case PEAP:
        {            
            writePEAPMethod(stream);
             break;
        }

        case TTLS:
        {   
            writeTTLSMethod(stream);                     
            break;
        }

    }
         
    file.close();
}

//-----------------------------------------------------------------------------------------------------------
//---------------- To write to stream the WEP Key Size Used -------------------------------------------------
//-----------------------------------------------------------------------------------------------------------
void FileManager::writeWEPSize(QTextStream &stream)
{
    switch( configData.getWep() )
    {
        case WEP1:
        {
            stream << "#WEP_KEY = 40\n\n";
            break;
        }
        case WEP2:
       {
           stream << "#WEP_KEY = 128\n\n";
           break;
       }
    }        
}

//-----------------------------------------------------------------------------------------------------------
//---------------- To write to stream the DHCP Method Used --------------------------------------------------
//-----------------------------------------------------------------------------------------------------------
void FileManager::writeDHCPMethod(QTextStream &stream)
{
    switch( configData.getDHCPType() )
    {
        case DHCPCD:
        {
            stream << "#DHCP TYPE = dhcpcd\n";
            break;
        }
        case DHCLIENT:
        {
            stream << "#DHCP TYPE = dhclient\n";            
            break;
        }
     }

     if ( configData.getDHCP() )
         //stream << "startup_command = <BEGIN_COMMAND>ifup-dhcp ra0<END_COMMAND>\n";
         stream << "startup_command = <BEGIN_COMMAND>" << dir << "dhcp<END_COMMAND>\n";
     else
         stream << "#startup_command = <BEGIN_COMMAND>" << dir << "dhcp<END_COMMAND>\n";
}

//-----------------------------------------------------------------------------------------------------------
//---------------- To write to stream the PEAP Config File Format -------------------------------------------
//-----------------------------------------------------------------------------------------------------------
void FileManager::writePEAPMethod(QTextStream &stream)
{     
    stream << "logfile = /var/log/xsupplicant.log\n\n";
    stream << "default_netname = " << configData.getSSID() << "\n";
    writeDHCPMethod(stream);
    stream << "first_auth_command = <BEGIN_COMMAND>echo \"Open1xSupplicant PEAP Method\"<END_COMMAND>\n";    
    
    QString aux("reauth_command = <BEGIN_COMMAND>iwconfig ");
    aux += configData.getInterface();
    aux += " essid ";
    aux += configData.getSSID();
    aux += " key ";
    switch( configData.getWep() )
    {
        case WEP1:
        {
            aux += "s:12345";
            break;
        }
        case WEP2:
       {
           aux += "s:1234567890qwe";
           break;
       }
    }      
    aux += "<END_COMMAND>\n";
    stream << aux;
    
    stream << "#INTERFACE = " << configData.getInterface() << "\n";
    stream << "network_list = " << configData.getSSID() << "\n\n";
    stream << configData.getSSID() << " {\n\n";
    stream << "  allow_types = eap-peap\n";
    stream << "  type = wireless\n";
    stream << "  wireless_control = yes\n\n";
    stream << "  identity = <BEGIN_ID>" << configData.getLogin() << "<END_ID>\n\n";
    stream << "  eap-peap {\n";
    stream << "        root_cert = NONE\n";
    stream << "        chunk_size = 1398\n";
    stream << "        random_file = /dev/urandom\n";
    stream << "        session_resume = yes\n\n";

    switch( configData.getSubMethod() )
    {
        case MSCHAPV2:
        {   
            stream << "        eap-mschapv2 {\n";
            stream << "            username = <BEGIN_UNAME>" << configData.getLogin() << "<END_UNAME>\n";
            stream << "            password = <BEGIN_PASS>" << configData.getPassword() << "<END_PASS>\n";
            stream << "        }\n";                     
            break;
        }
     } 
                 
     stream << "  }\n";
     stream << "}\n";     
}

//-----------------------------------------------------------------------------------------------------------
//---------------- To write to stream the TTLS Config File Format -------------------------------------------
//-----------------------------------------------------------------------------------------------------------
void FileManager::writeTTLSMethod(QTextStream &stream)
{  
    stream << "logfile = /var/log/xsupplicant.log\n\n";
    stream << "default_netname = " << configData.getSSID() << "\n";
    writeDHCPMethod(stream);
    stream << "first_auth_command = <BEGIN_COMMAND>echo \"Open1xSupplicant TTLS Method\"<END_COMMAND>\n";
    
    QString aux("reauth_command = <BEGIN_COMMAND>iwconfig ");
    aux += configData.getInterface();
    aux += " essid ";
    aux += configData.getSSID();
    aux += " key ";
    switch( configData.getWep() )
    {
        case WEP1:
        {
            aux += "s:12345";
            break;
        }
        case WEP2:
       {
           aux += "s:1234567890qwe";
           break;
       }
    }      
    aux += "<END_COMMAND>\n";
    stream << aux;
    
    stream << "#INTERFACE = " << configData.getInterface() << "\n";            
    stream << "network_list = " << configData.getSSID() << "\n\n";
    stream << configData.getSSID() << " {\n\n";
    stream << "  allow_types = eap-ttls\n";
    stream << "  type = wireless\n";
    stream << "  wireless_control = yes\n\n";
    stream << "  identity = <BEGIN_ID>" << configData.getLogin() << "<END_ID>\n\n";
    stream << "  eap-ttls {\n";
    stream << "        root_cert = NONE\n";
    stream << "        chunk_size = 1398\n";
    stream << "        random_file = /dev/urandom\n";
    stream << "        session_resume = yes\n";
  
    switch( configData.getSubMethod() )
    {
        case MSCHAPV2:
        {   
            stream << "        phase2_type = mschapv2\n\n";
            stream << "        mschapv2 {\n";
            stream << "            username = <BEGIN_UNAME>" << configData.getLogin() << "<END_UNAME>\n";
            stream << "            password = <BEGIN_PASS>" << configData.getPassword() << "<END_PASS>\n";
            stream << "        }\n";                     
            break;
        }
    } 
       
    stream << "  }\n";
    stream << "}\n";
}

//-----------------------------------------------------------------------------------------------------------
//---------------- To Clean the Config Fields in Open1xSupplicant -------------------------------------------
//-----------------------------------------------------------------------------------------------------------
void FileManager::cleanFields()
{       
       cSSID->setText("");
       uiLogin->setText("");
       uiPass->setText("");       
}

//-----------------------------------------------------------------------------------------------------------
//---------------- To Load Config Files if They Exist -------------------------------------------------------
//-----------------------------------------------------------------------------------------------------------
void FileManager::loadFile( const QString &filename )
{
    listView->clear();
    
    getInterfaces();    

    QFile file( filename );
         
    if ( !file.open( IO_ReadOnly ) )
    {
        newRegistry();
        return;
    }

    QTextStream stream( &file );
    stream.setEncoding(QTextStream::UnicodeUTF8);
    
    while ( !stream.atEnd() ) 
    {
        QString line =  stream.readLine();
        execParser(line);       
    }    
    
        
    newRegistry();
    
    file.close();
}

//-----------------------------------------------------------------------------------------------------------
//---------------- To Get the Interfaces in the Current System ----------------------------------------------
//-----------------------------------------------------------------------------------------------------------
void FileManager::getInterfaces()
{    
     int aux = cInterface->count()-1;
     for( int i = aux; i >= 0; i-- )
        cInterface->removeItem(i);       
    
//--- Only for wirwless Interfaces------------------------------------------------     
    QString command("iwconfig | grep ESSID | tr -s \" \" \":\" | cut -f1 -d\":\" > ");
    command += dir;
    command += "interfaces";
    int count = system( command );
    if ( count >= 0 )
    {
    
        command = dir;
        command += "interfaces";
        QFile file( command );
    
        if ( !file.open( IO_ReadOnly ) )
            return;
        QTextStream stream( &file );
        stream.setEncoding(QTextStream::UnicodeUTF8);
    
        QString line;
        while ( !stream.atEnd() ) 
        {
            cInterface->insertItem(stream.readLine());       
            count++;
        }    
    
        file.close();
    }
    if ( count <= 0 )
    {
        showMessage( lang->showMessage( MESSAGES, 1 ), WARNING );
//--- For all Network Interfaces---------------------------- 
        command = "ifconfig | grep \"Link encap\" | tr -s \" \" \":\" | cut -f1 -d\":\" > ";
        command += dir;
        command += "interfaces";
        count = system( command );
        if ( count >= 0 )
        {
    
            command = dir;
            command += "interfaces";
            QFile file( command );
    
            if ( !file.open( IO_ReadOnly ) )
                return;
            QTextStream stream( &file );
            stream.setEncoding(QTextStream::UnicodeUTF8);
    
            QString line;
            while ( !stream.atEnd() ) 
            {
                cInterface->insertItem(stream.readLine());       
                count++;
            }    
    
            file.close();
        }
        if ( count <= 0 )
        {
            showMessage( lang->showMessage( MESSAGES, 1 ), WARNING );
        }
    }    
}

//-----------------------------------------------------------------------------------------------------------
//---------------- To Get the Newtworks SSID ----------------------------------------------------------------
//-----------------------------------------------------------------------------------------------------------
void FileManager::getNetworksSSID()
{    
    infNet->clear();         
    
    String command = "ifconfig ";
    command += configData.getInterface();
    command += " allmulti up ";
    system(command);
    
//--- Only for wirwless Interfaces------------------------------------------------         
    command = "iwlist ";
    command += configData.getInterface();
    command += " scan | grep ESSID | cut -f2 -d'\"' > ";
    command += dir;  
    command += "ssids";     
    if ( system( command ) != -1 )
    {
    
        command = dir;
        command += "ssids";
        QFile file( command );
    
        if ( !file.open( IO_ReadOnly ) )
            return;
        QTextStream stream( &file );
        stream.setEncoding(QTextStream::UnicodeUTF8);
    
        QString line;
        uint count = 0;
        while ( !stream.atEnd() ) 
        {
            QString aux( stream.readLine() );
            if ( QString::compare( aux, " " ) == 0 )
            {
                infNet->insertItem( "#HIDE#" );
                count++;
            }
            else
            { 
                infNet->insertItem( aux );
                count++;
            }
        } 
        if ( count == 0 )   
            showMessage( lang->showMessage( MESSAGES, 2 ), WARNING );
        file.close();
    }
    else
        showMessage( lang->showMessage( MESSAGES, 2 ), WARNING );    
}

//-----------------------------------------------------------------------------------------------------------
//---------------- Return the Temp Directory Path -----------------------------------------------------------
//-----------------------------------------------------------------------------------------------------------
QString FileManager::getDir()
{
    return dir;
}

//-----------------------------------------------------------------------------------------------------------
//---------------- Parser to Read conf Files ----------------------------------------------------------------
//-----------------------------------------------------------------------------------------------------------
void FileManager::execParser( QString command )
{
    if ( command.contains("#WEP_KEY = 40",FALSE) > 0 )
        configData.setWep( WEP1 );
    if ( command.contains("#WEP_KEY = 128",FALSE) > 0 )
        configData.setWep( WEP2 );
    
    if ( command.contains("default_netname = ",FALSE) > 0 )
        configData.setSSID( command.remove("default_netname = ").simplifyWhiteSpace() );      
    if ( command.contains("startup_command",FALSE) > 0 )
        configData.setDHCP( TRUE );
    if ( command.contains("#startup_command",FALSE) > 0 )
        configData.setDHCP( FALSE ); 
    if ( command.contains("#INTERFACE",FALSE) > 0 )
        configData.setInterface( command.remove("#INTERFACE = ").simplifyWhiteSpace() );
  //------ Methods and SubMethods --------------  
    if ( command.contains("allow_types = ",FALSE) > 0 )
    {
        if ( QString::compare( command.remove("allow_types = ").simplifyWhiteSpace(), "eap-peap" ) == 0 )
            configData.setMethod(PEAP);   
        if ( QString::compare( command.remove("allow_types = ").simplifyWhiteSpace(), "eap-ttls" ) == 0 )
            configData.setMethod(TTLS);  
        isSubMethod = TRUE;
    }
    if ( command.contains("eap-mschapv2 {",FALSE) > 0 && isSubMethod)
    {
        configData.setSubMethod(MSCHAPV2);
        isSubMethod = FALSE;
    }
  //--------------------------------------------
    if ( command.contains("username = <BEGIN_UNAME>",FALSE) > 0 )
    {
        QString aux = command.remove("username = <BEGIN_UNAME>");
        configData.setLogin(aux.remove("<END_UNAME>").simplifyWhiteSpace());
    }
    if ( command.contains("password = <BEGIN_PASS>",FALSE) > 0 )
    {
        QString aux = command.remove("password = <BEGIN_PASS>");        
        configData.setPassword(aux.remove("<END_PASS>").simplifyWhiteSpace());                
    }  
    if ( command.contains("#DHCP TYPE",FALSE) > 0 )
    {
        QString aux = command.remove("#DHCP TYPE = ").simplifyWhiteSpace();
        if ( QString::compare( aux, "dhcpcd" ) == 0 )
            configData.setDHCPType( DHCPCD ); 
        if ( QString::compare( aux, "dhclient" ) == 0 )
            configData.setDHCPType( DHCLIENT ); 
    }
}

//-----------------------------------------------------------------------------------------------------------
//---------------- Draw the Tab Pannel with their Objects ---------------------------------------------------
//-----------------------------------------------------------------------------------------------------------
void FileManager::setupTabWidget()
{            
    //---Tab creation------------------------
    
    tabWidget = new QTabWidget( this );

    QWidget *userinfo = new QWidget( tabWidget );
    QGridLayout *grid1 = new QGridLayout( userinfo, 2, 6, 4, 4 );

    QLabel *lbLogin = new QLabel( lang->showMessage( LABELS, 0 ), userinfo );
    lbLogin->resize( lbLogin->sizeHint() );
    grid1->addWidget( lbLogin, 0, 0 );

    QLabel *lbPass = new QLabel( lang->showMessage( LABELS, 1 ), userinfo );
    lbPass->resize( lbPass->sizeHint() );
    grid1->addWidget( lbPass, 0, 1 );   

    submit = new QPushButton( lang->showMessage( BUTTONS, 0 ), userinfo );
    submit->resize( submit->sizeHint() );
    grid1->addWidget( submit, 0, 4 );
    connect( submit, SIGNAL( clicked() ), this, SLOT( startXsupplicant() ) );

    uiLogin = new QLineEdit( userinfo );
    uiLogin->resize( uiLogin->sizeHint() );
    grid1->addWidget( uiLogin, 1, 0 );
    lbLogin->setBuddy( lbLogin );

    uiPass = new QLineEdit( userinfo );
    uiPass->resize( uiPass->sizeHint() );
    grid1->addWidget( uiPass, 1, 1 );
    lbPass->setBuddy( lbPass );

    change = new QPushButton( lang->showMessage( BUTTONS, 1 ), userinfo );
    change->resize( change->sizeHint() );
    grid1->addWidget( change, 1, 4 );
    connect( change, SIGNAL( clicked() ), this, SLOT( changeRegistry() ) );

    tabWidget->addTab( userinfo, lang->showMessage( TABS, 0 ) );

    // --------------------------------------

    QWidget *config = new QWidget( this );
    QGridLayout *grid2 = new QGridLayout( config, 2, 6, 4, 4 );
        
    QLabel *lbInterface = new QLabel( lang->showMessage( LABELS, 2 ), config );
    lbInterface->resize( lbInterface->sizeHint() );
    grid2->addWidget( lbInterface, 0, 0 );

    QLabel *lbMethod = new QLabel( lang->showMessage( LABELS, 3 ), config );
    lbMethod->resize( lbMethod->sizeHint() );
    grid2->addWidget( lbMethod, 0, 1 );  
    
    QLabel *lbSSID = new QLabel( lang->showMessage( LABELS, 4 ), config );
    lbSSID->resize( lbSSID->sizeHint() );
    grid2->addWidget( lbSSID, 0, 2 );
    
    QLabel *lbSSIDList = new QLabel( lang->showMessage( LABELS, 5 ), config );
    lbSSIDList->resize( lbSSIDList->sizeHint() );
    grid2->addWidget( lbSSIDList, 0, 3 );
    
    
    QLabel *lbWEP = new QLabel( lang->showMessage( LABELS, 6 ), config );
    lbWEP->resize( lbWEP->sizeHint() );
    grid2->addWidget( lbWEP, 0, 4 );

    cDHCP = new QCheckBox( lang->showMessage( LABELS, 7 ), config );
    cDHCP->resize( cDHCP->sizeHint() );
    grid2->addWidget( cDHCP, 0, 5 );
        
    cInterface = new QComboBox( FALSE, config );    
    grid2->addWidget( cInterface, 1, 0 );
    lbInterface->setBuddy( lbInterface );

    cMethod = new QComboBox( FALSE, config );    
    grid2->addWidget( cMethod, 1, 1 );
    lbMethod->setBuddy( lbMethod );

    cSSID = new QLineEdit( config );
    cSSID->resize( cSSID->sizeHint() );
    grid2->addWidget( cSSID, 1, 2 );
    lbSSID->setBuddy( lbSSID ); 
    
    infNet = new QListBox( config ); 
    infNet->resize( infNet->sizeHint() );
    grid2->addWidget( infNet, 1, 3 );
    lbSSIDList->setBuddy( lbSSIDList );
    
    connect( infNet, SIGNAL( clicked( QListBoxItem* ) ), this, SLOT( ssidSelected( QListBoxItem* ) ) );
    
    cWEP = new QComboBox( FALSE, config );    
    grid2->addWidget( cWEP, 1, 4 );
    lbWEP->setBuddy( lbWEP );  
    
    cDHCPType = new QComboBox( FALSE, config );    
    grid2->addWidget( cDHCPType, 1, 5 );     
        
    tabWidget->addTab( config, lang->showMessage( TABS, 1 ) );

    mainGrid->addWidget( tabWidget, 0, 0 );
}

//-----------------------------------------------------------------------------------------------------------
//---------------- Draw the List View -----------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------------------
void FileManager::setupListView()
{ 
    listView = new QListView( this );
    listView->addColumn( lang->showMessage( LABELS, 2 ) );
    listView->addColumn( lang->showMessage( LABELS, 3 ) );
    listView->addColumn( lang->showMessage( LABELS, 4 ) );
    listView->addColumn( lang->showMessage( LABELS, 0 ) );
    listView->addColumn( lang->showMessage( LABELS, 1 ) );
    listView->addColumn( lang->showMessage( LABELS, 6 ) );
    listView->addColumn( lang->showMessage( LABELS, 7 ) );
    listView->addColumn( lang->showMessage( LABELS, 8 ) );

    listView->setSelectionMode( QListView::Single );

    connect( listView, SIGNAL( clicked( QListViewItem* ) ), this, SLOT( itemSelected( QListViewItem* ) ) );  
    
    mainGrid->addWidget( listView, 1, 0 );
    listView->setAllColumnsShowFocus( TRUE );           
}

//-----------------------------------------------------------------------------------------------------------
//---------------- Draw the Status Bar Above ----------------------------------------------------------------
//-----------------------------------------------------------------------------------------------------------
void FileManager::setupInfoWidget()
{                        
    infStatus = new QListBox( this );    
    
    mainGrid->addWidget( infStatus, 2, 0 );
    
    infStatus->insertItem( lang->showMessage(INFORMATIONS_CAB) );
}

//-----------------------------------------------------------------------------------------------------------
//---------------- Put a New Registry in the ConfigObject, in the List View and in the Fields ---------------
//-----------------------------------------------------------------------------------------------------------
void FileManager::newRegistry()
{
    QListViewItem *item = new QListViewItem( listView );
            
    setList(item);
    
    setFields();
}

//-----------------------------------------------------------------------------------------------------------
//---------------- Change the Data in Current Position in the ConfigObject and List View --------------------
//-----------------------------------------------------------------------------------------------------------
void FileManager::changeRegistry()
{      
    uint aux_method, aux_submethod;
    if ( QString::compare( cMethod->currentText(),"eap-peap(mschapv2)" ) == 0 )
    { 
        aux_method = PEAP;
        aux_submethod = MSCHAPV2;
    }
    if ( QString::compare( cMethod->currentText(),"eap-ttls(mschapv2)" ) == 0 ) 
    {
        aux_method = TTLS;
        aux_submethod = MSCHAPV2;
    }
    
    uint key;
    if ( QString::compare( cWEP->currentText(),"40" ) == 0 )  
        key = WEP1;  
    if ( QString::compare( cWEP->currentText(),"128" ) == 0 )  
        key = WEP2; 

    uint dhctp;
    if ( QString::compare( cDHCPType->currentText(),"dhcpcd" ) == 0 )  
        dhctp = DHCPCD;  
    if ( QString::compare( cDHCPType->currentText(),"dhclient" ) == 0 )  
        dhctp = DHCLIENT;
    
    QString pwd( configData.getPassword() );
    if ( isValidPwd() )
        pwd = uiPass->text();

    configData.setConfigObject(cInterface->currentText(), aux_method, aux_submethod, cSSID->text(), uiLogin->text(), pwd, key, cDHCP->isChecked(), dhctp);
        
    QListViewItem *item = listView->currentItem();
    
    setFields();
    setList(item);
}

//-----------------------------------------------------------------------------------------------------------
//-------------- To Stop DHCP Client Deamon in the Xsupplicant interface to avoid problems ------------------
//-----------------------------------------------------------------------------------------------------------
void FileManager::stopDHCP()
{
    xsupplicant.setInterface(configData.getInterface());
    if ( !xsupplicant.stopDHCP( configData.getDHCPType() ) )
        showMessage( lang->showMessage( MESSAGES, 3 ), WARNING );
    else
    {
        QString info( lang->showMessage( INFORMATIONS,0  ) );
        info.replace( "#INTF#",xsupplicant.getInterface() );                
        setInfo( info );        
    }
}

//-----------------------------------------------------------------------------------------------------------
//---------------- Start The Xsupplicant Program After Prepare Network Parameters ---------------------------
//-----------------------------------------------------------------------------------------------------------
void FileManager::startXsupplicant()
{               
    xsupplicant.setInterface(configData.getInterface());
    
    if ( !xsupplicant.isDHCP( configData.getDHCPType() ) && !xsupplicant.isXsupplicant() )
    {
        QString path(dir);
        path += "open1xsupplicant.conf";
        saveFile( path );            
        if ( xsupplicant.initNetwork( configData.getSSID(), 40 ) )    
            if ( !xsupplicant.startXsupplicant() )
                showMessage( lang->showMessage( MESSAGES, 4 ), WARNING );
            else
            {
                showMessage( lang->showMessage( MESSAGES, 5 ), INFORMATION );
                infoDHCP_Xsupp();
                getWirelessStatus();
            }
        else
            showMessage( lang->showMessage( MESSAGES, 6 ), WARNING );
    }
    else
        showMessage( lang->showMessage( MESSAGES, 7 ), WARNING );
}

//-----------------------------------------------------------------------------------------------------------
//-------------- To Stop Xsupplicant Deamon to avoid problems -----------------------------------------------
//-----------------------------------------------------------------------------------------------------------
void FileManager::stopXsupplicant()
{
    xsupplicant.setInterface(configData.getInterface());
    if ( !xsupplicant.stopXsupplicant( ) )
        showMessage( lang->showMessage( MESSAGES, 8 ), WARNING );
    else
        setInfo( lang->showMessage( INFORMATIONS,1  ) );   
}

//-----------------------------------------------------------------------------------------------------------
//---------------- To Put in Fields the Data Row Selected in List View --------------------------------------
//-----------------------------------------------------------------------------------------------------------
void FileManager::itemSelected( QListViewItem *item )
{
    if ( !item )
        return;
    item->setSelected( TRUE );
    item->repaint();
        
    setFields();
}

//-----------------------------------------------------------------------------------------------------------
//---------------- To Put in SSID Field the Network SSID Selected in SSID List ------------------------------
//-----------------------------------------------------------------------------------------------------------
void FileManager::ssidSelected( QListBoxItem *item )
{
    if ( !item )
        return;    
    if ( QString::compare( item->text(), "#HIDE#" ) != 0 ) 
      cSSID->setText( item->text() );
}

//-----------------------------------------------------------------------------------------------------------
//---------------- Put The Data in ConfigObject on the Fields -----------------------------------------------
//-----------------------------------------------------------------------------------------------------------
void FileManager::setFields()
{   
    if ( cMethod->count() <= 0 )
    {
        switch( configData.getMethod() )
        {
            case PEAP:
            {
                switch( configData.getSubMethod() )
                {
                    case MSCHAPV2:
                    {
                        cMethod->insertItem( "eap-peap(mschapv2)" );
                        break;
                    }
                }                
                cMethod->insertItem( "eap-ttls(mschapv2)" );
                break;
            }
    

            case TTLS:
            {
                switch( configData.getSubMethod() )
                {
                    case MSCHAPV2:
                    {
                        cMethod->insertItem( "eap-ttls(mschapv2)" );
                        break;
                    }
                }
                cMethod->insertItem( "eap-peap(mschapv2)" );
                break;
            }

        }
    }
    
    if ( cWEP->count() <= 0 )
    {
        switch( configData.getWep() )
        {
            case WEP1:
            {
                cWEP->insertItem( "40" );
                cWEP->insertItem( "128" );
                break;
            }
            case WEP2:
            {
                cWEP->insertItem( "128" );
                cWEP->insertItem( "40" );
                break;
            }
        }
    }
    
    cSSID->setText( configData.getSSID() );
    uiLogin->setText( configData.getLogin() );
    uiPass->setText( coverPassword( ) ); 
    cDHCP->setChecked( configData.getDHCP() );  
    
    if ( cDHCPType->count() <= 0 )
    {
        switch( configData.getDHCPType() )
        {
            case DHCPCD:
            {
                cDHCPType->insertItem( "dhcpcd" );
                cDHCPType->insertItem( "dhclient" );
                break;
            }
            case DHCLIENT:
            {
                cDHCPType->insertItem( "dhclient" );
                cDHCPType->insertItem( "dhcpcd" );
                break;
            }
        }
    }  
}

//-----------------------------------------------------------------------------------------------------------
//---------------- Put Data in the List View ----------------------------------------------------------------
//-----------------------------------------------------------------------------------------------------------
void FileManager::setList(QListViewItem *item)
{
    item->setText( 0, configData.getInterface() );
    
    QString method;
    switch( configData.getMethod() )
    {
        case PEAP:
        {
            method = "eap-peap";
            switch( configData.getSubMethod() )
            {
                case MSCHAPV2:
                {
                    method += "(mschapv2)";
                    break;
                }
            }     
            break;
        }

        case TTLS:
        {
            method = "eap-ttls";
            switch( configData.getSubMethod() )
            {
                case MSCHAPV2:
                {
                    method += "(mschapv2)";
                    break;
                 }
            }     
            break;
        }

    } 
    
    item->setText( 1, method );   
    item->setText( 2, configData.getSSID() );
    item->setText( 3, configData.getLogin() );
    item->setText( 4, coverPassword( ) );
    
    switch( configData.getWep() )
    {
        case WEP1:
        {
            item->setText( 5, "40" );                
            break;
        }
        case WEP2:
        {        
            item->setText( 5, "128" );
            break;
        }
    }
    
    if (configData.getDHCP())
        item->setText( 6, lang->showMessage( DHCP, 0 ) );
    else
        item->setText( 6, lang->showMessage( DHCP, 1 ) );

    switch( configData.getDHCPType() )
    {
        case DHCPCD:
        {
            item->setText( 7, "dhcpcd" );                
            break;
        }
        case DHCLIENT:
        {        
            item->setText( 7, "dhclient" );
            break;
        }
    }
    
}

//-----------------------------------------------------------------------------------------------------------
//---------------- Get Information About if the DHCP Deamon is working on Xsupplicant Interface -------------
//-----------------------------------------------------------------------------------------------------------
void FileManager::infoDHCP_Xsupp()
{
    if ( xsupplicant.isDHCP( configData.getDHCPType() ) )
    {
        QString info( lang->showMessage( INFORMATIONS, 2 ) );        
        info.replace( "#INTF#", configData.getInterface() );        
        setInfo( info );
    }
    else
    {
        QString info( lang->showMessage( INFORMATIONS, 3 ) );        
        info.replace( "#INTF#", configData.getInterface() );       
        setInfo( info );
    }
    if ( xsupplicant.isXsupplicant() )             
        setInfo( lang->showMessage( INFORMATIONS, 4 ) );
    else   
        setInfo( lang->showMessage( INFORMATIONS, 5 ) );
}


//-----------------------------------------------------------------------------------------------------------
//---------------- Indicate where is Wireless Interface Connected or if Ethernet Interface are connected  ---
//-----------------------------------------------------------------------------------------------------------
void FileManager::getWirelessStatus()
{
    QString line;    
    uint cont = 0;
    while ( !xsupplicant.showNetworkParam() )
    {
        cont++;
        if ( cont > 100000 )
            break;
    }
    
    if ( cont <= 100000 )
    {
        QString path(dir);
        path += "status";
        QFile file( path );
            if ( file.size() > 0 )  
            {               
                if ( !file.open( IO_ReadOnly ) )
                    return;
                QTextStream stream( &file );
                stream.setEncoding(QTextStream::UnicodeUTF8);
                
                line = lang->showMessage( INFORMATIONS,6  );
                line.replace( "#INTF#",configData.getInterface() );
                line += " ";                   
                while ( !stream.atEnd() )                 
                    line += stream.readLine();                                           
                file.close();
                setInfo( line );
            }
            else
            {
                line = lang->showMessage( INFORMATIONS,7  );
                line.replace( "#INTF#",configData.getInterface() );                             
                setInfo( line );
            }
     }
     else
     {
         line = lang->showMessage( INFORMATIONS,7  );
         line.replace( "#INTF#",configData.getInterface() );
         setInfo( line );
     }
}

//-----------------------------------------------------------------------------------------------------------
//---------------- Put information in information Box -------------------------------------------------------
//-----------------------------------------------------------------------------------------------------------
void FileManager::setInfo(const QString &message)
{
    QString aux( " " );
    aux += QString::number( infStatus->numRows() );
    aux += "->";
    aux += message;
    infStatus->insertItem( aux );
}

//-----------------------------------------------------------------------------------------------------------
//---------------- Display to User one type of Message ------------------------------------------------------
//-----------------------------------------------------------------------------------------------------------
void FileManager::showMessage(const QString &message, uint type)
{
    switch(type)
    {
        case ERROR:
        {
            QMessageBox::critical( 0,
                "FATAL ERROR",
                message,
                "SAIR" );
            exit( -1 );
            break;
        }
        case WARNING:
        {
            QMessageBox::warning( 0,
                "WARNING",
                message,
                1,0,0 );
            break;
        }
        case INFORMATION:
        {
            QMessageBox::information( 0,
                "INFORMATION",
                message,
                1,0,0 );
            break;
        }
    }
}

//-----------------------------------------------------------------------------------------------------------
//---------------- Cover User Password ----------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------------------
QString FileManager::coverPassword( )
{
    QString newPass;
    for ( uint i = 0; i < configData.getPassword().length(); i++ )
        newPass += "*";
    return newPass;
}

//-----------------------------------------------------------------------------------------------------------
//---------------- Verify if Password was put by User -------------------------------------------------------
//-----------------------------------------------------------------------------------------------------------
bool FileManager::isValidPwd( )
{
    QString aux;
    
    for ( uint i = 0; i < uiPass->text().length(); i++ )
        aux += "*";     
    
    if ( QString::compare( uiPass->text(), aux ) == 0 )
        return FALSE;
    return TRUE;
}

//-----------------------------------------------------------------------------------------------------------
//---------------- Create a file to run dhcp client deamon --------------------------------------------------
//-----------------------------------------------------------------------------------------------------------
void FileManager::createDHCPFile(const QString &interface)
{
    QString path(dir);
    path += "dhcp";
    QFile file( path );
    if ( !file.open( IO_WriteOnly ) )
            return;

    QTextStream stream( &file );
    stream.setEncoding(QTextStream::UnicodeUTF8);
    
    stream << "#! /bin/bash\n\n";
    stream << "#This file is to start dhcp client deamon.\n\n";
    
    switch( configData.getDHCPType() )
    {
        case DHCPCD:
        {
            stream << "#DHCP TYPE = dhcpcd\n";            
            //stream << "startproc -f -t 5 -q /sbin/dhcpcd -t 999999 " << interface; 
            stream << "/sbin/dhcpcd -t 999999 " << interface;
            stream << " &";
            break;
        }
        case DHCLIENT:
        {
            stream << "#DHCP TYPE = dhclient\n";
            //stream << "startproc -f -t 5 -q /sbin/dhclient " << interface;
            stream << "/sbin/dhclient " << interface;  
            stream << " &";
            break;
        }
    }
        
    stream << "\n\nexit $R_SUCCESS";
    file.close();  
    
    QString command("chmod a+x ");
    command += dir;
    command += "dhcp";
    system(command);
}

//-----------------------------------------------------------------------------------------------------------
//---------------- Create One README File in the Temporary directory ----------------------------------------
//-----------------------------------------------------------------------------------------------------------
void FileManager::createReadmeFile()
{
    QString path(dir);
    path += "README";
    QFile file( path );
    if ( !file.exists() )            
    {          
        if ( !file.open( IO_WriteOnly ) )
            return;

        QTextStream stream( &file );
        stream.setEncoding(QTextStream::UnicodeUTF8);
    
        stream << "#***************************************************************************\n";
        stream << "#*   Copyright (C) 2005 by Paulo Ferreira and Bruno Tome                   *\n";
        stream << "#*   acfpaulo@gmail.com , tome.bruno@gmail.com                             *\n";
        stream << "#*                                                                         *\n";
        stream << "#*   This program is free software; you can redistribute it and/or modify  *\n";
        stream << "#*   it under the terms of the GNU General Public License as published by  *\n";
        stream << "#*   the Free Software Foundation; either version 2 of the License, or     *\n";
        stream << "#*   (at your option) any later version.                                   *\n";
        stream << "#*                                                                         *\n";
        stream << "#*   This program is distributed in the hope that it will be useful,       *\n";
        stream << "#*   but WITHOUT ANY WARRANTY; without even the implied warranty of        *\n";
        stream << "#*   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *\n";
        stream << "#*   GNU General Public License for more details.                          *\n";
        stream << "#*                                                                         *\n";
        stream << "#*   You should have received a copy of the GNU General Public License     *\n";
        stream << "#*   along with this program; if not, write to the                         *\n";
        stream << "#*   Free Software Foundation, Inc.,                                       *\n";
        stream << "#*   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *\n";
        stream << "#***************************************************************************\n\n";
        stream << "#Welcom to the Open1xSupplicant interface. This interface is to help you to\n";
        stream << " create config files to operate with Xsupplicant ( a supplicant to 802.1x\n";
        stream << " protocol ).\n\n";
        stream << "#This interface create this hidden directory to save the backup filies\n";
        stream << " including the configuration file. Please don't erase this directory neither\n";
        stream << " the files in it.";
 
        file.close();
    }
}

