/* GAdmin-OpenVPN - An easy to use GTK+ frontend for the openvpn client.
 * Copyright (C) 2008 - 2012 Magnus Loef <magnus-swe@telia.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 3 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.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
*/


#include "../config.h"
#include <gtk/gtk.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include "widgets.h"
#include "gettext.h"
#include "show_info.h"
#include "commands.h"
#include "activate_button_clicked.h"
#include "apply_client_settings.h"
#include "populate_log_tab.h"

extern gchar *selected_connection;

extern int activated;



void activate_button_clicked(struct w *widgets)
{
    gchar *info, *path = NULL;
    int i = 0;
    G_CONST_RETURN gchar *cacert;
    G_CONST_RETURN gchar *cert;
    G_CONST_RETURN gchar *key;

    if( activated )
        return;

    /* Get the ca cert, cert and key names */
    cacert = gtk_entry_get_text(GTK_ENTRY(widgets->client_set_entry[5]));
    cert   = gtk_entry_get_text(GTK_ENTRY(widgets->client_set_entry[6]));
    key    = gtk_entry_get_text(GTK_ENTRY(widgets->client_set_entry[7]));

    /* See if we have the required minimum certs and keys */
    for(i=0; i<3; i++)
    {
        if( i == 0 )
            path = g_strdup_printf("%s/client/%s/certs/%s", OPENVPN_SYSCONF_DIR, selected_connection, cacert);
        if( i == 1 )
            path = g_strdup_printf("%s/client/%s/certs/%s", OPENVPN_SYSCONF_DIR, selected_connection, cert);
        if( i == 2 )
            path = g_strdup_printf("%s/client/%s/certs/%s", OPENVPN_SYSCONF_DIR, selected_connection, key);

        if( ! file_exists(path) )
        {
            info = g_strdup_printf(_("Import server certificates in the client settings first.\n"));
            show_info(info);
            g_free(info);
            g_free(path);
            return;
        }
        g_free(path);
    }

    /* Switch to the notebooks progress/log tab */
    gtk_notebook_set_current_page(GTK_NOTEBOOK(widgets->main_notebook), 1);

    /* Start the gadmin-openvpn-client runlevel script and
       make it start at boot if specified. */
    init_start(widgets);

    /* Sleep 5 seconds and then populate it */
    sleep(5);
    populate_log_tab(widgets);
}
