/* GAdmin-Rsync - An easy to use GTK+ frontend for the rsync backup client and server.
 * Copyright (C) 2007-2011 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 <string.h>
#include <stdlib.h>
#include "widgets.h"
#include "gettext.h"
#include "allocate.h"
#include "show_info.h"

extern int MAX_READ_POPEN;



void set_version(struct w *widgets)
{
    FILE *fp;
    char *line;
    int  i=0, rsync_found = 0;
    long count = 0;
    gchar *command;
    gchar *ver=NULL;
    gchar *utf8=NULL;
    gchar *info;
    GdkColor color;

    /* Rsync check */
    command = g_strdup_printf("%s --version 2>&1", RSYNC_BINARY);
    if((fp=popen(command, "r"))==NULL)
    {
        info = g_strdup_printf(_("Set version failed\n"));
        show_info(info);
        g_free(info);
        g_free(command);
        return;
    }
    g_free(command);    

    line = allocate(MAX_READ_POPEN);
    while(fgets(line, MAX_READ_POPEN, fp)!=NULL)
    {
        if( strstr(line, "rsync") && strstr(line, "version") && strlen(line) < 100 )
	{
    	    rsync_found = 1;

	    count = 0;    	    
    	    for(i=0; line[i]!='\0'; i++)
    	    {
    	        if( (line[i]==' ' || line[i]=='\t') 
    	        &&  (line[i+1]!=' ' || line[i+1]!='\t') )
    	          count++;

    	        if( count >= 4 )
    	          break;
	    }
	    line[i]='\0';
	    
    	    ver = g_strdup_printf(_(" Information: %s"), line);
	    utf8 = g_locale_to_utf8(ver, strlen(ver), NULL, NULL, NULL);
    	    gtk_label_set_text(GTK_LABEL(widgets->version_label), utf8);
	    g_free(utf8);
    	}
    }
    pclose(fp);
    free(line);

    /* Set info text */
    if( ! rsync_found )
    {
	// Fixme: Make it red.
        ver = g_strdup_printf(_(" Information: Rsync is not installed or not in your path."));
	utf8 = g_locale_to_utf8(ver, strlen(ver), NULL, NULL, NULL);
        gtk_label_set_text(GTK_LABEL(widgets->version_label), utf8);
	g_free(utf8);

	/* Set status color */
	gdk_color_parse("red", &color);
	gtk_widget_modify_fg(widgets->version_label, GTK_STATE_NORMAL, &color);
    }    

    g_free(ver);
}
