/*****************************************************************************
 * Copyright (C) 2004-2009 Christoph Thielecke <crissi99@gmx.de>             *
 *                                                                           *
 * 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 package 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 package; if not, write to the Free Software               *
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA *
 *****************************************************************************/

#include "generateopenvpnkeydialog.h"

#include <QUrl>
#include <QtCore/QString>
#include <QtCore/QFile>

#include <kdialog.h>
#include <klocale.h>
#include <kmessagebox.h>
#include <ktemporaryfile.h>
#include <kurl.h>
#include <kurlrequester.h>

#include <unistd.h>

GenerateOpenvpnKeyDialog::GenerateOpenvpnKeyDialog(KVpncConfig *GlobalConfig, QWidget *parent, const QString& caption)
        : KDialog(parent)
{
    Q_UNUSED(caption);

    QWidget *page = new QWidget(this);
    setMainWidget(page);
    main = new Ui_GenerateOpenvpnKeyDialogBase;
    main->setupUi(page);
    this->GlobalConfig = GlobalConfig;
    filename = "";
    genOk = false;


    main->FilenameUrlrequester->setFilter("*.key");

}

GenerateOpenvpnKeyDialog::~GenerateOpenvpnKeyDialog()
{
//  delete generateOpenvpnKeyProcess;
}

void GenerateOpenvpnKeyDialog::accept()
{
    filename = main->FilenameUrlrequester->url().toLocalFile();
    if (!filename.isEmpty()) {
        canAccept();
    }

    else {
        GlobalConfig->appendLogEntry(i18n("GenerateOpenvpnKeyDialog: empty filename."), KVpncEnum::error);
        KMessageBox::sorry(0, i18n("Filename cannot be empty."), i18n("Empty Filename"));
    }
}


void GenerateOpenvpnKeyDialog::canAccept()
{

    /*
     QFile f( filename );
     if ( !f.exists() )
     {
      KMessageBox::information( 0, i18n( "File not found." ), i18n( "No fFile" ) );

      //  emit progress( 100 );
      return ;
     }*/
    generateOpenvpnKeyProcess = new QProcess(0);
    QString proc = GlobalConfig->pathToOpenvpn;
    QStringList args;
    args.append("--genkey");
    args.append("--secret");
    args.append(filename);

    connect(generateOpenvpnKeyProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readStdErr()));
    connect(generateOpenvpnKeyProcess, SIGNAL(readyReadStandardError()), this, SLOT(readStdErr()));
	env = new QStringList();
	*env << "LC_ALL=C" << "LANG=C" << "PATH=/bin:/usr/bin:/usr/sbin:/sbin";
    generateOpenvpnKeyProcess->setEnvironment(*env);
    generateOpenvpnKeyProcess->start(proc, args);
    if (!generateOpenvpnKeyProcess->waitForStarted()) {
        KMessageBox::sorry(this, i18n("Failed to generate key %1." ,  QString("openvpn")));
        GlobalConfig->appendLogEntry(i18n("Failed to start \"%1\"." ,  QString("openvpn")), KVpncEnum::error);
    } else {
        GlobalConfig->appendLogEntry(i18n("Generating key %1 was successful.", QString("openvpn")), KVpncEnum::info);
        genOk = true;
    }

    generateOpenvpnKeyProcess->waitForFinished();

    disconnect(generateOpenvpnKeyProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readStdErr()));
    disconnect(generateOpenvpnKeyProcess, SIGNAL(readyReadStandardError()), this, SLOT(readStdErr()));
    delete generateOpenvpnKeyProcess;
    generateOpenvpnKeyProcess = 0L;

    if (genOk)
        KMessageBox::information(this, i18n("Generating the key in \"%1\" was successful." ,  filename));
    else
        KMessageBox::sorry(this, i18n("Generating the key in \"%1\" failed." ,  filename));
    QDialog::accept();
}

void GenerateOpenvpnKeyDialog::readStdOut()
{
	if (generateOpenvpnKeyProcess) {
		QStringList msg_list = QString(generateOpenvpnKeyProcess->readAllStandardOutput()).split('\n');
		for (int i = 0; i < msg_list.size(); ++i) {
			QString msg = msg_list.at(i);

		}
	}
}

void GenerateOpenvpnKeyDialog::readStdErr()
{
	if (generateOpenvpnKeyProcess) {
		QStringList msg_list = QString(generateOpenvpnKeyProcess->readAllStandardError()).split('\n');
		for (int i = 0; i < msg_list.size(); ++i) {
			QString msg = msg_list.at(i);

			if (msg.indexOf("Permission denied", 0) > -1) {
				if (GlobalConfig->KvpncDebugLevel > 0)
					GlobalConfig->appendLogEntry("[openvpn genkey err] " + msg, KVpncEnum::error);
				genOk = false;
				//}
			}
		}
	}
}

#include "generateopenvpnkeydialog.moc"
