/* GAdmin-OpenVPN - An easy to use GTK+ frontend for the openvpn server.
 * 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 <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <gtk/gtk.h>
#include "gettext.h"
#include "widgets.h"
#include "allocate.h"
#include "show_info.h"
#include "commands.h"
#include "file_chooser.h"
#include "show_import_window.h"
#include "make_settings_buttons.h"
#include "make_settings_entries.h"
#include "populate_gadmin_openvpn.h"


/* Apply import button */
void apply_import_clicked(struct w *widgets)
{
    int import_type = 0;
    gchar *info, *cmd, *path;
    G_CONST_RETURN gchar *import_package_file;
    G_CONST_RETURN gchar *import_config_file;

    import_package_file = gtk_entry_get_text(GTK_ENTRY(widgets->import_package_file_entry));
    import_config_file = gtk_entry_get_text(GTK_ENTRY(widgets->import_config_file_entry));

    /* Both import types cannot be selected at the same time */
    if( import_package_file!=NULL && strlen(import_package_file) > 3
    &&	import_config_file!=NULL  && strlen(import_config_file)  > 3 )
    {
        info = g_strdup_printf(_("Error: Both import types can not be used at the same time.\n"));
        show_info(info);
        g_free(info);
        return;
    }

    /* No valid import directory supplied */
    if( import_package_file!=NULL && strlen(import_package_file) > 3 )
    {
        import_type = 1;
    }
    else
    if( import_config_file!=NULL || strlen(import_config_file) > 3 )
    {
        import_type = 2;
    }
    else
    {
        info = g_strdup_printf(_("Error: Path length is too short.\n"));
        show_info(info);
        g_free(info);
        return;
    }


    /* Package import sanity check */
    if( import_type == 1 && ! strstr(import_package_file, ".tar.gz") )
    {
        info = g_strdup_printf(_("Error: Import package should be a compressed .tar.gz package.\n"));
        show_info(info);
        g_free(info);
        return;
    }

    /* Create the import directory */
    cmd = g_strdup_printf("mkdir -p %s/client/Imported-Setup", OPENVPN_SYSCONF_DIR);
    if( ! run_command(cmd) )
    {
        info = g_strdup_printf(_("Could not create a new setup directory.\n"));
        show_info(info);
        g_free(info);
        return;
    }
    g_free(cmd);

    if( import_type == 1 )
    {
        cmd = g_strdup_printf("tar -zxf %s -C %s/client/Imported-Setup", import_package_file, OPENVPN_SYSCONF_DIR);
        if( ! run_command(cmd) )
        {
            info = g_strdup_printf(_("Error: Unpacking client setup package has failed.\n"));
            show_info(info);
            g_free(info);
            return;
        }
        g_free(cmd);

        /* The package from the server export has its setup files in the "client" directory.
           Move the files from that directory one level up so that the client will find them. */
        path = g_strdup_printf("%s/client/Imported-Setup/client", OPENVPN_SYSCONF_DIR);
        if( file_exists(path) && strlen(path) > 20 )
        {
            cmd = g_strdup_printf("mv %s/* %s/client/Imported-Setup", path, OPENVPN_SYSCONF_DIR);
            if( ! run_command(cmd) )
            {
                info = g_strdup_printf(_("Error: Moving client setup package has failed.\n"));
                show_info(info);
                g_free(info);
                g_free(cmd);
                g_free(path);
                return;
            }
            g_free(cmd);

            /* Remove the client directory */
            cmd = g_strdup_printf("rm -rf %s", path);
            if( ! run_command(cmd) )
            {
                info = g_strdup_printf(_("Error: Removing client setup package.\n"));
                show_info(info);
                g_free(info);
                g_free(cmd);
                g_free(path);
                return;
            }
            g_free(cmd);
        }
        g_free(path);

        /* Chmod the certs to 600 */
        cmd = g_strdup_printf("chmod 600 %s/client/Imported-Setup/certs/*", OPENVPN_SYSCONF_DIR);
        if( ! run_command(cmd) )
        {
            info = g_strdup_printf(_("Warning: Could not change certificate file mode.\n"));
            show_info(info);
            g_free(info);
            /* Just a warning, dont return. */
        }
        g_free(cmd);
    }

    if( import_type == 2 )
    {
        /* Set connection name in the conf, dont set it as selected. */
        cmd = g_strdup_printf("echo \"# Connection_name: Imported-Setup\n\" > %s/client/Imported-Setup/%s",
			        OPENVPN_SYSCONF_DIR, "gadmin-openvpn-client.conf");
        if( ! run_command(cmd) )
        {
            info = g_strdup_printf(_("Error: Adapting the client configuration file failed.\n"));
            show_info(info);
            g_free(info);
            return;
        }
        g_free(cmd);

        /* Copy the client configuration file to the client directory */
        cmd = g_strdup_printf("cat %s >> %s/client/Imported-Setup/%s",
			        import_config_file, OPENVPN_SYSCONF_DIR, "gadmin-openvpn-client.conf");
        if( ! run_command(cmd) )
        {
            info = g_strdup_printf(_("Error: Copying the client configuration file.\n"));
            show_info(info);
            g_free(info);
            return;
        }
        g_free(cmd);
    }

    /* Populate the entire gui */
    populate_gadmin_openvpn(widgets);

    /* Destroy the import window */
    gtk_widget_destroy(widgets->import_window);
}

/* Select an import package */
void select_package_file_clicked(struct w *widgets)
{
    gchar *path = NULL;

    path = get_dialog_path_selection("FILE", "/home", "None");
    if( path!=NULL )
    {
        gtk_entry_set_text(GTK_ENTRY(widgets->import_package_file_entry), path);
        g_free(path);
    }
}

/* Select a configuration file to import */
void select_config_file_clicked(struct w *widgets)
{
    gchar *path = NULL;

    path = get_dialog_path_selection("FILE", "/home", "None");
    if( path!=NULL )
    {
        gtk_entry_set_text(GTK_ENTRY(widgets->import_config_file_entry), path);
        g_free(path);
    }
}


/* Show the import window */
void show_import_window(struct w *widgets)
{
    GtkWidget *frame;
    GtkWidget *table;
    GtkWidget *vbox;
    GtkWidget *dir_select_button;
    GtkWidget *cancel_button, *apply_button;
    gchar *info;
    int a=0, b=1;

    GtkTooltips *tooltips;
    tooltips = gtk_tooltips_new();

    if( tooltips != NULL ) // Fixes not used warning.
    { }

    widgets->import_window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
    gtk_window_set_position(GTK_WINDOW(widgets->import_window), GTK_WIN_POS_CENTER);
    gtk_widget_set_size_request(widgets->import_window, 540, -1);

    /* Set window information */
    info = g_strdup_printf(_("GAdmin-OpenVPN-Server - Import connection"));
    gtk_window_set_title(GTK_WINDOW(widgets->import_window), info);
    g_free(info);

    vbox = gtk_vbox_new(FALSE, 0);
    gtk_container_add(GTK_CONTAINER(widgets->import_window), vbox);

    tooltips = gtk_tooltips_new();

    /* 1 tables with some settings and 2 columns */
    table = gtk_table_new(2, 2, FALSE);

    frame = gtk_frame_new(_("Select a connection type to import:"));

    gtk_box_pack_start(GTK_BOX(vbox), frame, TRUE, TRUE, 1);
    gtk_container_add(GTK_CONTAINER(frame), table);

    /* Import a package file */
    widgets->import_package_file_entry = gtk_entry_new();
    dir_select_button = make_button_with_entry(GTK_TABLE(table),
				        widgets->import_package_file_entry,
				        "gtk-refresh",
				        _("Import package:"),
    _("Select a connection setup tar.gz package with a configuration file and certificates to import"),
				        0,1,a,b,350);
    a++; b++;
    g_signal_connect_swapped(G_OBJECT(dir_select_button), "clicked",
	         G_CALLBACK(select_package_file_clicked), widgets);


    /* Import a single configuration file */
    widgets->import_config_file_entry = gtk_entry_new();
    dir_select_button = make_button_with_entry(GTK_TABLE(table),
				        widgets->import_config_file_entry,
                                            "gtk-refresh",
                          _("Import configuration file:"),
               _("Select a configuration file to import"),
                                               0,1,a,b,350);
    a++; b++;
    g_signal_connect_swapped(G_OBJECT(dir_select_button), "clicked",
	         G_CALLBACK(select_config_file_clicked), widgets);

    /* Buttons: "Cancel" and "Apply" */
    GtkWidget *hbutton_box = gtk_hbutton_box_new();
    gtk_button_box_set_layout(GTK_BUTTON_BOX(hbutton_box), GTK_BUTTONBOX_SPREAD);

    cancel_button = gtk_button_new_from_stock(GTK_STOCK_QUIT);
    apply_button = gtk_button_new_from_stock(GTK_STOCK_APPLY);

    gtk_box_pack_start(GTK_BOX(hbutton_box), cancel_button, FALSE, FALSE, 0);
    gtk_box_pack_start(GTK_BOX(hbutton_box), apply_button, FALSE, FALSE, 0);
    gtk_container_add(GTK_CONTAINER(vbox), hbutton_box);

    /* Window exit signal */
    g_signal_connect(GTK_WINDOW(widgets->import_window), "delete_event",
                     G_CALLBACK(gtk_widget_destroy), NULL);

    /* Cancel button */
    g_signal_connect_swapped((gpointer)cancel_button, "clicked",
            G_CALLBACK(gtk_widget_destroy), GTK_OBJECT(widgets->import_window));

    /* Apply button signals */
    g_signal_connect_swapped((gpointer)apply_button, "clicked",
	     G_CALLBACK(apply_import_clicked), widgets);


    gtk_widget_show_all(widgets->import_window);
}
