/* 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 "support.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "allocate.h"
#include "widgets.h"
#include "populate_log_tab.h"
#include "show_info.h"

extern gchar *selected_connection;



void populate_log_tab(struct w *widgets)
{
    /* Populates the VPN log tab */
    FILE *fp;
    long file_size;
    char *line;
    GtkTreeIter iter;
    GtkTreePath *path;
    gboolean edit=0;
    int found = 0;
    gchar *utf8=NULL, *log_path;

    gtk_list_store_clear(widgets->log_store);

    log_path = g_strdup_printf("%s/log/gadmin-openvpn/client/%s/openvpn-client.log", LOCALSTATEDIR, selected_connection);

    if((fp=fopen(log_path, "r"))==NULL) 
    {
        /* Dont show popup */
        g_free(log_path);
        return;
    }
    fseek(fp, 0, SEEK_END);
    file_size = ftell(fp);
    rewind(fp);

    line = allocate(file_size+1);

    if( file_size > 1 )
    while(fgets(line, file_size, fp)!=NULL)
    {
        if( line[strlen(line)-1]=='\n' )
            line[strlen(line)-1]='\0';

        found = 1;

        gtk_list_store_append(GTK_LIST_STORE(widgets->log_store), &iter);
        utf8 = g_locale_to_utf8(line, strlen(line), NULL, NULL, NULL);
        gtk_list_store_set(GTK_LIST_STORE(widgets->log_store), &iter, 0, utf8, -1);
        if(utf8!=NULL)
            g_free(utf8);
    }
    fclose(fp);
    free(line);
    g_free(log_path);

    if( ! found )
        return;

    path = gtk_tree_path_new_first();
    gtk_tree_view_set_cursor(GTK_TREE_VIEW(widgets->log_treeview), path, NULL, edit);
    gtk_tree_path_free(path);
}
