/*
    This file is part of audtty, copyright 2008-2010 Chris Taylor.

    audtty 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.

    audtty 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 audtty; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/

#include <audacious/audctrl.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <glib.h>
#include "main.h"
#include "dbus.h"
#include "settings.h"
#include "kbd_constants.h"
#include "curses_printf.h"

void check_env(void);
void fix_env(void);
static const gchar *dbussessionaddr = "DBUS_SESSION_BUS_ADDRESS";
static const gchar *xsession = "DISPLAY";


void check_env(void){
	if(g_getenv(dbussessionaddr)==NULL||g_getenv(xsession)==NULL)
		fix_env();
	else
		return;
}

void fix_env(void){
        gchar *dbussession = "/.dbus/session-bus/";
	GDir *dir;
        gchar *name;
        GError *open_error=NULL;
	gchar *dbus;

	gchar *check = NULL;
	FILE *filename;
	gchar buffer[4096];

	dbus=g_strdup(g_get_home_dir());
	dbus=g_strconcat(dbus,dbussession,NULL);
	dir = g_dir_open(dbus,0,&open_error);

	if(!dir){
		printf("%s",open_error->message);
		exit(1);
	}
        
	while((name=(gchar*)g_dir_read_name(dir))){
		g_dir_close(dir);
		dbus=g_strconcat(dbus,name,NULL);
		filename=fopen(dbus,"r");
		if(!filename){
			printf("Failed to open file: %s \n",name);
		}
		else{
			while(fgets(buffer,4096,filename)){
				if(buffer[0]=='#')
					continue;
				else{
					if((check=strchr(buffer,'=')))
					{
						gchar *env=(gchar*)strtok(buffer,"=");
						gchar *val=(gchar*)strtok(NULL, "\n");
						if((g_strcmp0(env,dbussessionaddr))==0)
						{
							g_setenv(env,val,0);
							g_setenv(xsession,":0",0); //Simply needs to be set.
							break;
						}
						else
							continue;
                                                g_free(env);
                                                g_free(val);
					}
					else
						continue;
				}
			}
		fclose(filename);
		break;
		}
	}
        if(open_error)
            g_free(open_error);
        g_free(dbus);
        g_free(dir);
	return;
}