/* ***********************IMPORTANT *********************************************
 *  Copyright (C) 2004-2007 Thierry Lagarde <tlagarde@users.sourceforge.net>
 *  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 2 of the License.
 *
 *
 *                      ********************
 *
 *
 *  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 Library General Public License for more details.
 *
 *
 *                      ********************
 *
 *
 * You are highly encouraged to send your changes to <tlagarde@users.sourceforge.net>
 * for possible incorporation into the main distribution.
 * By sending these changes to <tlagarde@users.sourceforge.net>,
 * it is assumed that you are offering <tlagarde@users.sourceforge.net>
 * the unlimited, non-exclusive right to reuse, modify, and relicense the code.
 *
 *
 *                      ********************
 *
 *  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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 **************************************************************************************/
#include "Tools.h"
#include "Debug.h"
#include "Macro.h"

#ifndef         __WINDOWS_ENABLE

#include <execinfo.h>
#include <malloc.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

gboolean Test_Droit_Execution(const char *executable){
	static struct stat _stat;

	if(stat(executable,&_stat)) return FALSE;
	if((_stat.st_mode&(S_IXGRP|S_IXUSR|S_IXOTH|S_ISUID|S_ISGID)) 
	 	&&S_ISREG(_stat.st_mode)) return TRUE;
	return FALSE;
}

char *Cherche_Chemin_Executable(char *commande)
{
	char *path,*chemin_commande,*s,*saveptr;

	path = getenv("PATH");
	if(!path) return NULL; 
	path = g_strdup(path);
	if(!path) return NULL;
	s = strtok_r(path,":", &saveptr);// on recupere la première repertoire dans le path
	while(s) {
		chemin_commande = g_strdup_printf ("%s/%s",s,commande);
		if(Test_Droit_Execution(chemin_commande)) { 
			MYFREE(path);
			return chemin_commande;
		}
		MYFREE(chemin_commande);
		s = strtok_r(0,":", &saveptr);//cherche dans le prochain chemin dans path...
	}
	MYFREE(path);
	return NULL;
}
#endif
