################################################################################
#                                                                              #
#   Copyright (C) 2008-2012 LABBE Corentin <corentin.labbe@geomatys.fr>
#
#    YASAT 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.
#
#    YASAT 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 YASAT.  If not, see <http://www.gnu.org/licenses/>.
#                                                                              #
################################################################################
#
# The display function is originated from lynis Copyright 2007-2009, Michael Boelen (michael@rootkit.nl), The Netherlands
# Web site: http://www.rootkit.nl
#
#################################################################################
#
# Common functions for YASAT
#
#################################################################################
#

	NORMAL="[0;39m"
	WARNING="[1;31m"
	YELLOW="[1;33m"
	BLUE="[0;36m"
	WHITE="[1;37m"
	GREEN="[0;32m"
	RED="[1;31m"
	ORANGE="[0;33m"
	NOIRGRAS="[1;39m"

#All results in orange/yellow is a optionnal warning
#All results in red must be corrected

################################################################################
################################################################################
print_color_chart()
{
	echo "Color chart"
	echo "$GREEN GREEN $NORMAL  is for good configuration or information"
	echo "$RED RED $NORMAL    is for configuration that must be corrected"
	echo "$ORANGE ORANGE $NORMAL is for optional configuration that can be done"
#ugly color, do not use:)
#	echo "$YELLOW YELLOW $NORMAL is for optional configuration that can be done"
	echo "$BLUE BLUE $NORMAL   is for information"
}


################################################################################
################################################################################
Display()
{
	INDENT=0; TEXT=''; RESULT=''; COLOR=''; ADVICE=''
	ECHOCMD="echo -e"
	if [ "`echo -e plop`" = '-e plop' ] ;then
		#with /bin/sh or zsh no -e
		ECHOCMD='echo'
	fi
        while [ $# -ge 1 ]; do
	    case $1 in
	        --color)
		    shift
		        case $1 in
			GREEN)
			  	COLOR=$GREEN;HTMLCOLOR='GREEN'
				if [ $PRINT_LEVEL -ge 2 ]
				then
					return 1;
				fi
			;;
			  RED)     COLOR=$RED;HTMLCOLOR='RED'     ;;
			  WHITE)   COLOR=$WHITE   ;;
			  YELLOW)
			  	COLOR=$YELLOW;HTMLCOLOR='YELLOW'
				if [ $PRINT_LEVEL -ge 3 ]
				then
					return 1;
				fi
			  ;;
			  ORANGE)
			  	COLOR=$ORANGE;HTMLCOLOR='ORANGE'
				if [ $PRINT_LEVEL -ge 3 ]
				then
					return 1;
				fi
			;;
			  BLUE)
			  	COLOR=$BLUE;HTMLCOLOR='BLUE'
				if [ $PRINT_LEVEL -ge 1 ]
				then
					return 1;
				fi
			  ;;
			esac
		;;
	        --indent)
		    shift
		    INDENT=$1
	        ;;
		--no-break | --nobreak | -nb)
		    ECHOCMD="echo -en"
		;;
		--result)
		    shift
		    RESULT=$1
		;;
		--advice)
		    shift
		    ADVICE=$1
		;;
	        --text)
	            shift
	            TEXT=$1
	        ;;
		*)
		    echo "INVALID OPTION (Display): $1, it is usually a bug of yasat (shame on me)"
		    exit 1
		;;
	    esac
	    # Go to next parameter
	    shift
	done
	if [ -z "${ADVICE}" -o "${ADVICE}" = 'NONE' ] ;then
		ADVICEVALUE=''
	else
		ADVICEVALUE="`grep ${ADVICE}= ${YASAT_ROOT}/yasat.advices | cut -d\= -f2-`"
		if [ -z "$ADVICEVALUE" ] ;then
			Display --indent 2 --text "BUG ADVICEVALUE is empty for ${ADVICE}" --result WARNING --color RED --advice YASAT_BUG
		fi
		if [ -z "`echo ${RESULT} | grep -vEi 'warning$|found$'`" ] ;then
			echo "= ${TEXT}" >> $REPORT_OUTPUT
		else
			echo "= ${TEXT} Result=${RESULT}" >> $REPORT_OUTPUT
		fi
		echo "  $ADVICEVALUE" >> $REPORT_OUTPUT
		report_add "${ADVICE}" TEXT $REPORT_OUTPUT
	fi

	if [ ! -z "$HTML_OUTPUT" ] ;then
		echo "<tr><td><b>${TEXT}</b></td><td> <FONT color=$HTMLCOLOR >${RESULT}</font></td><td>$ADVICEVALUE</td></tr>" >> "$HTML_OUTPUT"
		if [ ! -z "$ADVICE" ] ;then
			report_add "${ADVICE}" HTML "$HTML_OUTPUT"
		fi
	fi

	if [ -z "${RESULT}" ]
	then
		echo 'ERROR No --result'
		return 1;
	fi
	RESULTPART=" [ ${COLOR}${RESULT}${NORMAL} ]"
	#size of result is 5 ( [  ]) + 8 (NOTFOUND/WARNING is the greatest result)
	MAXLINESIZE=67
	if [ ! "${TEXT}" = "" ]
	then
        	# Display
		LINESIZE=`echo "${TEXT}" | wc -c | tr -d ' '`
		SPACES=`expr ${MAXLINESIZE} - ${INDENT} - ${LINESIZE}`
		if [ "$SPACES" -le 0 ] ;then
			TEXT1=`echo ${TEXT} | cut -b -50`
			LINESIZE=`echo "${TEXT1}" | wc -c | tr -d ' '`
			SPACES=`expr ${MAXLINESIZE} - ${INDENT} - ${LINESIZE}`
			${ECHOCMD} "\033[${INDENT}C${TEXT1}\033[${SPACES}C${RESULTPART}\t${ADVICEVALUE}"
			TEXT2=`echo ${TEXT} | cut -b 51-`
			${ECHOCMD} "!!\033[${INDENT}C${TEXT2}"
		else
			SPACES=`expr ${MAXLINESIZE} - ${INDENT} - ${LINESIZE}`
			ADVICE_LINE_SIZE=0
			if [ -z "${ADVICEVALUE}" ] ;then
				FULLLINESIZE=$LINESIZE
			else
				ADVICE_LINE_SIZE=`echo "${ADVICEVALUE}" | wc -c | tr -d ' '`
				FULLLINESIZE=`expr ${ADVICE_LINE_SIZE} + 80`
			fi
			Debug "FULL $FULLLINESIZE $LINESIZE $SPACES adv=$ADVICE_LINE_SIZE"
			if [ $FULLLINESIZE -gt $COL_WIDTH ]
			then
				${ECHOCMD} "\033[${INDENT}C${TEXT}\033[${SPACES}C${RESULTPART}"
				${ECHOCMD} "\033[${INDENT}C\t-> ${ADVICEVALUE}"
			else
				${ECHOCMD} "\033[${INDENT}C${TEXT}\033[${SPACES}C${RESULTPART}\t${ADVICEVALUE}"
			fi
		fi
	else
		echo "Missing parameter ${TEXT}"
	fi
}
################################################################################
################################################################################
report_add()
{
	if [ -z "$1" ]
	then
		Display --indent 2 --text "Missing argument #1 for report_add" --result WARNING --color RED --advice YASAT_BUG
		return -1;
	fi
	if [ -z "$2" ]
	then
		Display --indent 2 --text "Missing argument #2 (type of output) for report_add" --result WARNING --color RED --advice YASAT_BUG
		return -1;
	fi
	if [ -z "$3" ]
	then
		Display --indent 2 --text "Missing argument #3 (name of the output file) for report_add" --result WARNING --color RED --advice YASAT_BUG
		return -1;
	fi

	Debug "report_add() called with $1 $2 $3"
	
#	if [ $2 = "TEXT" ]
#	then
#		echo "" >> $3
#		echo "==  `cat yasat.advices |grep $ADVICE | cut -d\= -f2-` ==" >> $3
#		echo "" >> $3
#	fi
	if [ $2 = "HTML" ]
	then
		echo "<tr><td>" >> "$3"
	fi

	ADVICEFOUND=0
	LISTE_ADVICE="`ls ${PLUGINS_REP}/*.advice`"
	cat $LISTE_ADVICE |
	while read line
	do
		if [ "$line" = "ADVICEEND" ]
		then
			ADVICEFOUND=0
		fi
		#temporary
		if [ ! -z "`echo $line |grep ^${ADVICELANG},`" ]
		then
			ADVICEFOUND=0
		fi

		if [ $ADVICEFOUND -eq 1 ]
		then
			if [ $2 = "TEXT" ]
			then
				echo "  $line" | sed 's/<[^>]*>//g'>> "$3"
			fi
			if [ $2 = "HTML" ]
			then
				echo "  $line" >> "$3"
				echo "<br>" >> "$3"
			fi
		fi

		if [ ! -z "`echo $line |grep ${ADVICELANG},$1`" ]
		then
			ADVICEFOUND=1
		fi
	done
	if [ $2 = "HTML" ]
	then
		echo "<br></td><td></td><td></td></tr>" >> "$3"
	fi


}

################################################################################
################################################################################
Debug()
{
	if [ $DEBUG -eq 1 ] ; then
		ECHOCMD="echo -e"
		if [ "`echo -e plop`" = '-e plop' ] ;then
			#with /bin/sh or zsh no -e
			ECHOCMD='echo'
		fi
		$ECHOCMD "$1"
	fi
}

################################################################################
################################################################################
# Find where the apache config is
# No argument
Find_apache_conf_location()
{
for LOCATION in ${POSSIBLE_APACHE_CONFIG_LOCATION}
do
	if [ -e "${LOCATION}/apache.conf" -o -e "${LOCATION}/httpd.conf" ]
	then
		export APACHE_CONF_REP="${LOCATION}"
		return 0;
	fi
done
	export APACHE_CONF_REP='NOTFOUND'
	return 1;
}

################################################################################
################################################################################
#arg 1 is the path to file createe by prepare_apache_conf()
#arg2 is the value found by FindValueOf
Check_apache_user()
{
export RESULTAT=''
export FINDERROR=''
if [ -z "$1" ] ; then
	Display --indent 2 --text "Missing argument #1 for Check_apache_user" --result WARNING --color RED --advice YASAT_BUG
	return 2;
fi
if [ -z "$2" ] ; then
	Display --indent 2 --text "Missing argument #2 for Check_apache_user" --result WARNING --color RED --advice YASAT_BUG
	return 2;
fi

if [ "`echo $2 | cut -b1`" = '$' ] ;then
	Display --indent 2 --text "Apache user is a variable" --result INFO --color BLUE
	#we ll find the value of this variable (only debian do that, and values can be found in /etc/apache2/envvars)
	if [ -e /etc/apache2/envvars ] ; then
		export RESULTAT="`grep APACHE_RUN_USER /etc/apache2/envvars | cut -d\= -f2`"
		if [ -z "$RESULTAT" ] ; then
			Display --indent 4 --text "Fallback to www-data" --result INFO --color BLUE
			export RESULTAT='www-data'
		fi
	else
		#TODO fallback to a common value
		Display --indent 4 --text "Fallback to www-data" --result INFO --color BLUE
		export RESULTAT='www-data'
	fi
	return 0;
	Display --indent 2 --text "Apache user is " --result "$RESULTAT" --color BLUE
fi
export RESULTAT="$2"
}
################################################################################
################################################################################
#arg 1 is the path to file createe by prepare_apache_conf()
#arg2 is the value found by FindValueOf
Check_apache_group()
{
export RESULTAT=''
export FINDERROR=''
if [ -z "$1" ] ; then
	Display --indent 2 --text "Missing argument #1 for Check_apache_group" --result WARNING --color RED --advice YASAT_BUG
	return 2;
fi
if [ -z "$2" ] ; then
	Display --indent 2 --text "Missing argument #2 for Check_apache_group" --result WARNING --color RED --advice YASAT_BUG
	return 2;
fi

if [ "`echo $2 | cut -b1`" = '$' ] ; then
	Display --indent 2 --text "Apache group is a variable" --result INFO --color BLUE
	#we ll find the value of this variable (only debian do that, and values can be found in /etc/apache2/envvars)
	if [ -e /etc/apache2/envvars ] ; then
		export RESULTAT="`grep APACHE_RUN_GROUP /etc/apache2/envvars | cut -d\= -f2`"
		if [ -z "$RESULTAT" ] ; then
			Display --indent 4 --text "Fallback to www-data" --result INFO --color BLUE
			export RESULTAT='www-data'
		fi
	else
		#TODO fallback to a common value
		Display --indent 4 --text "Fallback to www-data" --result INFO --color BLUE
		export RESULTAT='www-data'
	fi
	return 0;
	Display --indent 2 --text "Apache group is " --result "$RESULTAT" --color BLUE
fi
export RESULTAT="$2"
}

################################################################################
################################################################################
#Find value of a directive separated by space "$2 value"
# #1 is the file to scan
# #2 is the directive to seek
# #3 is a sort of error reporting, possible values JUSTTEST(what a bad name choice) and MULTIPLE(allow multiple value)
# #4 is case sensitivity flag (nothing = sensitive, INSENSITIVE otherwise)
FindValueOf()
{
export RESULTAT=''
export FINDERROR=''
if [ -z "$1" ] ; then
	Display --indent 2 --text "Missing argument FindValueOf() #1 (conf file to scan)" --result WARNING --color RED --advice YASAT_BUG
	return 2;
fi

if [ -z "$2" ] ; then
	Display --indent 2 --text "Missing argument FindValueOf #2 (directive to seek)" --result WARNING --color RED --advice YASAT_BUG
	return 2;
fi
TEMP=""
Debug "Seek value of $2 in $1"
if [ ! -e "$1" ] ;then
	echo "Error $1 do not exist"
	return 1;
fi
#End of checks of parameters
DO_INSENSITIVE=0
if [ $# -ge 4 ] ; then
	if [ "$4" = 'INSENSITIVE' ] ; then
		DO_INSENSITIVE=1
	fi
fi
if [ $DO_INSENSITIVE -ge 1 ] ; then
	TEMP=`grep -rih "^[[:space:]]*$2[[:space:]]" $1 |grep -v '^[[:space:]]*#' |tr '[:upper:]' '[:lower:]' |sed "s/^[[:space:]]*$2[[:space:]]*//g" |sed 's/#.*//g'`
else
	TEMP=`grep -rih "^[[:space:]]*$2[[:space:]]" $1 |grep -v '^[[:space:]]*#' |sed "s/^[[:space:]]*$2[[:space:]]*//g" |sed 's/#.*//g'`
fi

if [ -z "$TEMP" ] ;then
	if [ $# -le 2 ] ; then
		Display --indent 2 --text "No declaration of $2" --result WARNING --color RED
	else
		if [ -z "$3" ] ;then
			Display --indent 2 --text "No declaration of $2" --result WARNING --color RED
			return 1;
		fi
	fi
fi
if [ `echo "$TEMP" | wc -l` -ge 2 ];then
	if [ "$3" = 'MULTIPLE' ] ; then
#		export RESULTAT="`echo $TEMP | sed "s/[[:space:]]*$2[[:space:]]*//g"`"
		export RESULTAT="$TEMP"
		return 0;
	fi
	Display --indent 2 --text "Error multiple declarations of $2" --result WARNING --color RED --advice GLOBAL_MULTIPLE_DECLARATIONS
	grep -ri "^[[:space:]]*$2[[:space:]]" $1 |grep -v '^[[:space:]]*#' |
	while read line
	do
		echo "  ==> $line"
	done
	export FINDERROR='MULTIPLE'
	export RESULTAT=`echo "$TEMP" | sort | uniq | head -n 1 |sed "s/^[[:space:]]*$2[[:space:]]*//g" | sed 's/#.*//g'`
	return 3;
fi

if [ `echo "$TEMP" | wc -l` -eq 0 ] ; then
	if [ -z "$3" ] ;then
		Display --indent 2 --text "No declaration of $2" --result WARNING --color RED
		return 1;
	fi
fi

if [ `echo "$TEMP" | wc -l` -eq 1 ] ;then
#	export RESULTAT=`echo "${TEMP}" | sed "s/^[[:space:]]*[a-zA-Z0-9][a-zA-Z0-9]*[[:space:]]*//g" | sed 's/#.*//g'`
#	export RESULTAT=`echo "${TEMP}" | sed "s/^[[:space:]]*$2[[:space:]]*//g" | sed 's/#.*//g'`
	export RESULTAT="${TEMP}"
fi
return 0;

}


#========================================================================================
#========================================================================================
#Find value type "$2 = value"
FindValueOfEqual()
{
RESULTAT=''
if [ "$1x" = "x" ]
then
	Display --indent 2 --text "Missing argument #1 (conf file to scan) of FindValueOfEqual" --result WARNING --color RED --advice YASAT_BUG
	return 2;
fi

if [ "$2x" = "x" ]
then
	Display --indent 2 --text "Missing argument #2 (directive to scan) of FindValueOfEqual" --result WARNING --color RED --advice YASAT_BUG
	return 2;
fi

TEMP=""
Debug "cherche la valeur de $2 dans $1"
TEMP=`grep -rih "^[[:space:]]*$2[[:space:]]*="  $1`

if [ -z "$TEMP" ]
then
	if [ "$3x" = "x" ]
	then
	Display --indent 2 --text "No declarations of $2 " --result WARNING --color RED
	return 1;
	fi
fi
if [ `echo "$TEMP" | wc -l` -ge 2 ]
then
	Display --indent 2 --text "Error multiple declarations of $2 " --result WARNING --color RED --advice GLOBAL_MULTIPLE_DECLARATIONS
	return 3;
fi

if [ `echo "$TEMP" | wc -l` -eq 0 ]
then
	if [ "$3x" = "x" ]
	then
	Display --indent 2 --text "No declarations of $2 " --result WARNING --color RED
	return 1;
	fi
fi

if [ `echo "$TEMP" | wc -l` -eq 1 ]
then
	export RESULTAT=`echo $TEMP | sed "s/^[[:space:]]*$2[[:space:]]*=[[:space:]]*//g"  | sed 's/[#;].*//g'`
fi

return 0;
}


#========================================================================================
#========================================================================================
#Find value type "$2 : value"
FindValueOfDDot()
{
RESULTAT=''
if [ "$1x" = "x" ]
then
	Display --indent 2 --text "Missing argument #1" --result WARNING --color RED --advice YASAT_BUG
	return 2;
fi

if [ "$2x" = "x" ]
then
	Display --indent 2 --text "Missing argument #2" --result WARNING --color RED --advice YASAT_BUG
	return 2;
fi

TEMP=""
Debug "cherche la valeur de $2 dans $1"
TEMP=`grep -rih "^[[:space:]]*$2[[:space:]]*:"  $1`

if [ -z "$TEMP" ]
then
	if [ "$3x" = "x" ]
	then
	Display --indent 2 --text "No declarations of $2 " --result WARNING --color RED
	return 1;
	fi
fi
if [ `echo "$TEMP" | wc -l` -ge 2 ]
then
	Display --indent 2 --text "Error multiple declarations of $2 " --result WARNING --color RED --advice GLOBAL_MULTIPLE_DECLARATIONS
	return 3;
fi

if [ `echo "$TEMP" | wc -l` -eq 0 ]
then
	if [ "$3x" = "x" ]
	then
	Display --indent 2 --text "No declarations of $2 " --result WARNING --color RED
	return 1;
	fi
fi

if [ `echo "$TEMP" | wc -l` -eq 1 ]
then
	export RESULTAT=`echo $TEMP | sed "s/^[[:space:]]*$2[[:space:]]*:[[:space:]]*//g" | sed 's/#.*//g'`
fi

return 0;
}











################################################################################
################################################################################

CheckPresenceOf()
{
if [ "$1x" = "x" ]
then
	Display --indent 2 --text "Missing argument #1" --result WARNING --color RED --advice YASAT_BUG
fi

if [ "$2x" = "x" ]
then
	Display --indent 2 --text "Missing argument #1" --result WARNING --color RED --advice YASAT_BUG
fi

TEMP=""
Debug "cherche si $2 est dans $1"
TEMP=`grep -rih "^ *$2"  $1`

if [ -z "$TEMP" ]
then
	if [ "$3x" = "x" ]
	then
	Display --indent 2 --text "No declarations of $2 " --result WARNING --color RED
	fi
fi
if [ `echo "$TEMP" | wc -l` -ge 2 ]
then
	Display --indent 2 --text "Error multiple declarations of $2 " --result WARNING --color RED --advice GLOBAL_MULTIPLE_DECLARATIONS
fi

if [ `echo "$TEMP" | wc -l` -eq 0 ]
then
	if [ "$3x" = "x" ]
	then
	Display --indent 2 --text "No declarations of $2 " --result WARNING --color RED
	fi
fi

if [ `echo "$TEMP" | wc -l` -eq 1 ]
then
	export RESULTAT=`echo $TEMP | sed "s/^.*$2\ //g" | cut -d\  -f1`
##	echo "=>$RESULTAT<="
fi
}















################################################################################
################################################################################

Title()
{
	if [ -z "$1" ]
	then
		echo "Error missing parameter for Title()"
		return 1;
	fi
	echo "=== $1 ==="
	if [ ! -z "$HTML_OUTPUT" ]
	then
		echo "</table><h1>$1</h1><br><table border='1'>" >> "$HTML_OUTPUT"
	fi
	if [ ! -z "$REPORT_OUTPUT" ]
	then
		echo '' >> $REPORT_OUTPUT
		echo "=== $1 ===" >> $REPORT_OUTPUT
	fi
}

################################################################################
################################################################################

#affiche_rouge()
#{
#	echo -e "\033[31m $1 \033[0m "
#}

################################################################################
################################################################################

#affiche_vert()
#{
#	echo -e "\033[0;32m $1 \033[0m "
#}

################################################################################
################################################################################

#affiche_orange()
#{
#	echo -e "\033[0;33m $1 \033[0m "
#}

################################################################################
################################################################################

print_help()
{
	echo "====================================="
	echo "== YASAT                           =="
	echo "== Yet Another Stupid Audit Tool   =="
	echo "==                                 =="
	echo "== Copyright (C) 2008-2012         =="
	echo "== LABBE Corentin                  =="
	echo "============================================================"
	echo "|Available options                                         |"
	echo "|                                                          |"
	echo "|  --standard          (-s) Do standard test               ====="
	echo "|  --list              (-l) List plugins available             |"
	echo "|  --debug             (-d) print debug informations           |"
	echo "|  --help              (-h) show this help                     ====="
	echo "|  --html              (-H) export YASAT 's results in html        |"
	echo "|                           default to ~/yasat/yasat.html          |"
	echo "|  --html-output PATH       PATH is the name of html file to write |"
	echo "|  --advice-lang LANG       LANG is the 2letter digit of the lang  |"
	echo "|                           (default is EN )                       |"
	echo "|  --full-scan         (-f) Do extra (long) tests (lots of find)   |"
	echo "|  --plugins-dir PATH  (-P) Set the path to the plugins to use     |"
	echo "|                           (default is ./plugins )                |"
	echo "|  --nopause           (-a) Do not make a pause after plugin's end |"
	echo "|  --plugin PATH       (-1) Just use the plugin pointed by PATH    |"
	echo "|  --Plugin NAME       (-p) Just use the plugin named NAME (TODO)  |"
	echo "|  --print-level X          Just print infos equal or above the    |"
	echo "|                           level X (All = 0 (default), infos = 1  |"
	echo "|                           warnings(orange) = 2, errors(red) = 3  |"
	echo "|  --skip                   Test(s) to skip, without the .test     |"
	echo "|                           (ex: --skip nfs,ntp) comma separated   |"
	echo "|  --check-update           Check if an update of YASAT exists     |"
	echo "|  --send-support           Same as --check-support but you will   |"
	echo "|                           send also your OS version as parameter |"
	echo "|                                                                  |"
	echo "| Thanks for using YASAT.                                          |"
	echo "|                                                                  |"
	echo "===================================================================="
}

################################################################################
################################################################################
#compare 2 right 
#example compare_right 666 640 YES said bad
#example compare_right 666 640 YES said bad
#example compare_right 400 640 NO said bad
#example compare_right 400 640 YES said good
#if arg #3 is NO, we want that $1 and $2 is stricly equal
compare_right()
{
#	RESULTAT='ERROR'
	if [ -z "$1" ] ; then
		echo "ERROR compare_right() missing arg #1 (right to test)"
		return 1;
	fi
	if [ -z "$2" ] ; then
		echo "ERROR compare_right() missing arg #2 (right wanted)"
		return 1;
	fi
	if [ -z "$3" ] ; then
		echo "ERROR compare_right() missing arg #3 (accept or not more restricted right)"
		return 1;
	fi
	WANT_U="`echo $2 | cut -c1`"
	TEST_U="`echo $1 | cut -c1`"
	WANT_G="`echo $2 | cut -c2`"
	TEST_G="`echo $1 | cut -c2`"
	WANT_O="`echo $2 | cut -c3`"
	TEST_O="`echo $1 | cut -c3`"
#	echo "$WANT_U vs $TEST_U"
	if [ $TEST_U -gt $WANT_U ] ; then
		return 2
	else
		if [ "$3" = 'NO' -a $TEST_U -lt $WANT_U ]; then
			return 3
		fi
	fi
#	echo "$WANT_G vs $TEST_G"
	if [ $TEST_G -gt $WANT_G ] ; then
		return 2
	else
		if [ "$3" = 'NO' -a $TEST_G -lt $WANT_G ]; then
			return 3
		fi
	fi
#	echo "$WANT_O vs $TEST_O"
	if [ $TEST_O -gt $WANT_O ] ; then
		return 2
	else
		if [ "$3" = 'NO' -a $TEST_O -lt $WANT_O ]; then
			return 3
		fi
	fi
#	RESULTAT='GOOD'
	return 0
}

################################################################################
################################################################################

#864000s = 1DAY
#2592000 = 30DAYS
check_certificate()
{
	if [ ! -e "$1" ] ; then
		echo "ERROR check_certificate() $1 do not exist"
		return 1;
	fi

	if [ -z "$2" ] ; then
		echo "ERROR check_certificate() missing #2"
		return 1;
	fi

	#command not found return error code 127
	openssl version> /dev/null 2>> $ERROR_OUTPUT_FILE
	if [ $? -eq 127 ] ; then
		Display --indent $2 --text "No openssl binary" --result WARNING --color RED
		return 1;
	fi
	$ECHOCMD -n "\033[${2}C" && openssl x509 -in $1 -noout -enddate

	openssl x509 -in $1 -noout -checkend 2592000
	if [ $? -eq 1 ] ; then
		Display --indent $2 --text "Cert < 1 month " --result WARNING --color RED --advice CERTIFICATE_OUTDATED
		#if < 1 month check for < 1 week
		openssl x509 -in $1 -noout -checkend 604800
		if [ $? -eq 1 ] ; then
			Display --indent $2 --text "Cert < 1 week " --result WARNING --color RED --advice CERTIFICATE_OUTDATED
		else
			Display --indent $2 --text "Cert > 1 week " --result OK --color GREEN
		fi
	else
		Display --indent $2 --text "Cert > 1 month " --result OK --color GREEN
	fi
}
################################################################################
################################################################################
#check that a private key is well owned (generally root:root 600)
#check also if it is password protected
# arg1 is the file to be tested
# arg2 is the indent for display
# arg3 is the application type (optionnal)
# arg4 is the owner (optionnal)
# arg5 is the group (optionnal)
check_private_key()
{
	if [ ! -e "$1" ] ; then
		echo "ERROR check_private_key() $1 do not exist"
		return 1;
	fi

	if [ -z "$2" ] ; then
		echo "ERROR check_private_key() missing #2 (indent)"
		return 1;
	fi
	#TODO 600 is perhaps a bit too much, some OS have a sslcert/sslpriv group (and also ldap, mail)
	if [ $# -ge 3 ] ; then
		if [ "$3" = 'ssh' ] ; then
			check_a_file "$1" "$2" "$4" "$5" 600
		else
			check_a_file "$1" "$2" root root 600
		fi
	fi
	
	openssl version> /dev/null 2>> $ERROR_OUTPUT_FILE
	if [ $? -eq 127 ] ; then
		Display --indent $2 --text "No openssl binary" --result WARNING --color RED
		return 1;
	fi
	PASSWORD_PROTECTED='no'
	#sshd could not use password protected key
	if [ $# -ge 3 ] ; then
		if [ "$3" != 'sshd' -a "$3" != 'ssh' ] ; then
			#for the moment, I just test for this Proc-Type: 4,ENCRYPTED to know if a private key is password protected
			if [ -z "`grep 'Proc-Type: 4,ENCRYPTED' $1`" ] ; then
				Display --indent $2 --text "$1 is not password protected" --result BAD --color ORANGE --advice GLOBAL_PRIVATE_KEY_NOT_PASSWORD_PROTECTED
			else
				Display --indent $2 --text "$1 is password protected" --result OK --color GREEN
				PASSWORD_PROTECTED='yes'
			fi
		fi
	fi
	TMP_RESULT="${TEMPYASATDIR}/ssl.out"
	KEYTYPE="`grep 'BEGIN.*PRIVATE KEY-----' $1 | cut -d\  -f2`"
	if [ "$KEYTYPE" = 'PRIVATE' ] ; then
		#ok, we have a file with no information, try with that
		openssl x509 -in $1 -text > "$TMP_RESULT" 2>> $ERROR_OUTPUT_FILE
		if [ $? -ne 0 ] ; then
			openssl rsa -in $1 -text > "$TMP_RESULT" 2>> $ERROR_OUTPUT_FILE
		fi
		if [ ! -z "`grep -i rsa $TMP_RESULT`" ] ; then
			KEYTYPE='RSA'
		fi
		rm "${TMP_RESULT}"
	fi
	if [ "$KEYTYPE" = 'RSA' ] ; then
		if [ "$PASSWORD_PROTECTED" = 'no' ] ; then
			openssl rsa -in $1 -text 2>> $ERROR_OUTPUT_FILE  > $TMP_RESULT
			if [ $? -eq 0 ] ; then
				KEYSIZE="`grep 'Private-Key' $TMP_RESULT |cut -d\  -f2 | cut -d\( -f2`"
				if [ $KEYSIZE -lt 2048 ] ; then
					Display --indent $2 --text "$1 keysize" --result $KEYSIZE --color RED --advice GLOBAL_RSA_KEY_SIZE
				else
					Display --indent $2 --text "$1 keysize" --result $KEYSIZE --color GREEN
				fi
			else
				Display --indent $2 --text "openssl error on $1" --result 'ERROR' --color RED --advice YASAT_BUG
			fi
		else
			Display --indent $2 --text "Cannot check size" --result 'SKIP' --color BLUE
		fi
#	else
		#it is a DSA or EC key
		#DSA key is 1024bits, so useless to test its size
	fi
	return $?

}

################################################################################
################################################################################

check_user_cron()
{
	if [ -z "$1" ]
	then
		echo 'Erreur manque argument de check_user_cron()'
	fi

	if [ -e "/var/spool/cron/$1" ]; then
		RESULTAT="YES"
	else
		RESULTAT="NO"
	fi
}

################################################################################
################################################################################

check_user_crontab()
{
	if [ -z "$1" ]
	then
		echo 'Erreur manque argument de check_user_cron()'
	fi
	RESULTAT=`crontab -l |grep -v 'no crontab for'`
}

################################################################################
################################################################################
#not finished
check_system_cron()
{
	grep -v '^#' /etc/crontab |
	while read line
	do
#		echo "$line"
		RESULTAT=`echo $line | awk '{print $7 }'`
		if [ ! -z "$RESULTAT" ]
		then
			TMP_CRONUSER=`echo $line | awk '{print $6 }'`
			echo "$line"
			echo "$TMP_CRONUSER"
		fi
	done
}
################################################################################
################################################################################
#Check file for
#
# $1 is the path to the file
# $2 is the indent
# $3 is the owner (or NULL)
# $4 is the group (or NULL)
# $5 is right
check_a_file()
{
	GOT_ERROR=0
	if [ -z "$1" ] ; then
		echo "ERROR check_a_file() missing parameter #1 (path to the file)"
		return 1;
	fi
	if [ ! -e "$1" ] ; then
		echo "ERROR check_a_file() $1 do not exists"
		return 1;
	fi
	if [ -z "$2" ] ; then
		echo "ERROR check_a_file() missing parameter #2"
		return 1;
	fi
	if [ -z "$3" ] ; then
		echo "ERROR check_a_file() missing parameter #3"
		return 1;
	fi
	if [ -z "$4" ] ; then
		echo "ERROR check_a_file() missing parameter #4"
		return 1;
	fi
	if [ -z "$5" ] ; then
		echo "ERROR check_a_file() missing parameter #5"
		return 1;
	fi
	if [ "$3" != 'NULL' ] ; then
		USER="`stat $STAT_USER $1`"
		if [ "$USER" != "$3" ] ; then
			Display --indent $2 --text "$1 is not $3 owned" --result WARNING --color RED
			GOT_ERROR=1
		fi
	fi
	if [ "$4" != 'NULL' ] ; then
		GROUP="`stat $STAT_GROUP $1`"
		if [ "$GROUP" != "$4" ] ; then
			Display --indent $2 --text "$1 is not $4 grouped" --result WARNING --color RED
			GOT_ERROR=1
		fi
	fi
	if [ "$5" != 'NULL' ] ; then
		RIGHT="`stat $STAT_RIGHT $1`"
		compare_right $RIGHT $5 YES
		if [ $? -ne 0 ] ; then
#		if [ "$RIGHT" != "$5" ] ; then
			Display --indent $2 --text "$1 is not $5 but $RIGHT" --result WARNING --color RED
			add_correction "chmod $5 $1"
			GOT_ERROR=1
		fi
	fi
	if [ $GOT_ERROR -eq 0 ] ; then
		Display --indent $2 --text "$1 is $3:$4 $RIGHT" --result GOOD --color GREEN
	fi
	return $GOT_ERROR
}

################################################################################
################################################################################
#Check file for
# - Not writable by others
# - Info when suid or other things
# - Not root:root owned
#
# $1 is the path to the file
# $2 is the indent
# $3 is the type (NORMAL PRIVKEY BINARY CERT etc..)
#

check_file()
{
	if [ "$1x" = "x" ] ; then
		echo "ERROR check_file() missing parameter #1"
		return 1;
	fi
	BINARY_TO_CHECK="$1"
	if [ "$2x" = "x" ] ; then
		echo "ERROR check_file() missing parameter #2"
		return 1;
	fi
	if [ "$3x" = "x" ] ; then
		echo "ERROR check_file() missing parameter #3"
		return 1;
	fi
	if [ ! -e "$1" ] ; then
		echo "ERROR check_file() $1 do not exist"
		return 1;
	fi
	if [ -L $1 ] ; then
		TARGET="`readlink $1`"
#		if [ "$TARGET" = "`basename $TARGET`" ] ; then
		if [ ! -z "`echo $TARGET |grep '\./' `" ] ; then
			BINARY_TO_CHECK="`dirname $1`/`readlink $1`"
		else
			BINARY_TO_CHECK="$TARGET"
		fi
		echo "Warning $1 is a link using $BINARY_TO_CHECK"
	fi
	GOOD=1
	USER="`stat $STAT_USER $BINARY_TO_CHECK`"
	GROUP="`stat $STAT_GROUP $BINARY_TO_CHECK`"
	RIGHT="`stat $STAT_RIGHT $BINARY_TO_CHECK`"
	RIGHT_L="`echo $RIGHT | wc -c`"
	if [ "$USER" != 'root' ] ; then
		Display --indent $2 --text "$BINARY_TO_CHECK is not root owned" --result WARNING --color RED --advice GLOBAL_FILE_MUST_BE_OWNED_BY_ROOT
		GOOD=0
		add_correction "chown root $BINARY_TO_CHECK"
	fi
	if [ "$GROUP" != "$ROOTGROUP" -a "$GROUP" != "ssl-cert" -a "$GROUP" != "keymastaa" ] ;then
		Display --indent $2 --text "$BINARY_TO_CHECK is not $ROOTGROUP (group) owned" --result WARNING --color RED --advice GLOBAL_FILE_MUST_BE_GROUPED_BY_ROOT
		GOOD=0
	fi
	if [ "$3" = "CERT" ] ; then
		check_certificate $BINARY_TO_CHECK $2
	fi
	if [ "$3" = "PRIVKEY" ] ; then
		check_private_key $BINARY_TO_CHECK $2
		if [ $? -ne 0 ] ; then
			GOOD=0
		fi
	fi

	if [ $RIGHT_L -ge 5 ] ;	then
	#not common right
		RIGHT_O="`echo $RIGHT | cut -b 4`"
		Display --indent $2 --text "$BINARY_TO_CHECK is a spetial binary (suid etc)" --result WARNING --color RED
		#TODO check what is spetial
	else
	#common right
		RIGHT_O="`echo $RIGHT | cut -b 3`"
		case $3 in
		PRIVKEY)
		if [ $RIGHT_O -ge 1 ] ; then
			Display --indent $2 --text "$BINARY_TO_CHECK is other accessible" --result WARNING --color RED --advice GLOBAL_FILE_OTHER_READABLE
			GOOD=0
		fi
		;;
		NORMAL)
		if [ $RIGHT_O -eq 7 -o $RIGHT_O -eq 6 ] ; then
			Display --indent $2 --text "$BINARY_TO_CHECK is other writable" --result WARNING --color RED --advice GLOBAL_FILE_OTHER_WRITABLE
			GOOD=0
		fi
		;;
		CERT)
		if [ $RIGHT_O -eq 7 -o $RIGHT_O -eq 6 ] ; then
			Display --indent $2 --text "$BINARY_TO_CHECK is other writable" --result WARNING --color RED --advice GLOBAL_FILE_OTHER_WRITABLE
			GOOD=0
		fi
		;;
		BINARY)
			if [ $RIGHT_O -eq 7 -o $RIGHT_O -eq 6 ] ; then
				Display --indent $2 --text "$BINARY_TO_CHECK is other writable" --result WARNING --color RED --advice GLOBAL_FILE_OTHER_WRITABLE
			fi
			#how about non-linux ?
			if [ -z "`readelf -h $BINARY_TO_CHECK 2>/dev/null| grep 'Type:'`" ] ; then
				Display --indent $2 --text "$BINARY_TO_CHECK isnt a binary according to readelf" --result BAD --color OR
			else
				#check for SSP and PIE
				readelf -s $BINARY_TO_CHECK | grep -q '__stack_chk_fail'
				if [ $? -eq 0 ] ; then
					Display --indent $2 --text "$BINARY_TO_CHECK have SSP" --result GOOD --color GREEN
				else
					Display --indent $2 --text "$BINARY_TO_CHECK havent SSP" --result BAD --color ORANGE --advice GLOBAL_BINARY_SSP
				fi
				readelf -h $BINARY_TO_CHECK | grep -q 'Type:[[:space:]]*DYN'
				if [ $? -eq 0 ] ; then
					Display --indent $2 --text "$BINARY_TO_CHECK is PIE" --result GOOD --color GREEN
				else
					Display --indent $2 --text "$BINARY_TO_CHECK isnt PIE" --result BAD --color ORANGE --advice GLOBAL_BINARY_PIE
				fi
			fi
			GOOD=0
		;;
		*)
		echo "ERROR unrecognized type"
		;;
		esac
	fi


	if [ $GOOD -eq 1 ] ; then
		Display --indent $2 --text "$BINARY_TO_CHECK $USER $GROUP $RIGHT" --result OK --color GREEN
	fi
}

################################################################################
################################################################################
#Check dir owner
# Param #1 is the PATH to be checked
# Param #2 is the user that must own the directory
# Param #3 is the file that get output of this function
# Param #4 is the indent value for print info
check_directory_owner()
{
	if [ -z "$1" ]
	then
		echo 'Error missing parameter #1 (PATH) for check_directory_owner()'
		return 1;
	fi
	if [ ! -e $1 ]
	then
		echo "check_directory_owner() Error $1 do not exist"
		return 1;
	fi
	if [ -z "$2" ]
	then
		echo 'Error missing parameter #2 (owner id) for check_directory_owner()'
		return 1;
	fi
	if [ -z "$3" ]
	then
		echo 'Error missing parameter #3 (path to the output) for check_directory_owner()'
		return 1;
	fi
	if [ -z "$4" ]
	then
		echo 'Error missing parameter #4 (indent) for check_directory_owner()'
		return 1;
	fi
	find "$1" ! -user $2 > $3
		RESULTAT=`cat $3 | wc -l`
		if [ $RESULTAT -eq 0 ]
		then
			Display --indent $4 --text "Owner of $1" --result OK --color GREEN
		else
			Display --indent $4 --text "$RESULTAT files have invalid owning != $2 in $1" --result WARNING --color RED --advice $5
		fi

}



################################################################################
################################################################################
#Check that a directory is group-ed by a group
# Param #1 is the PATH to be checked
# Param #2 is the group that must own the directory
# Param #3 is the file that get output of this function
# Param #4 is the indent value for print info

check_directory_group()
{
	if [ -z "$1" ] ;then
		echo 'Error missing parameter #1 (PATH) for check_directory_group()'
		return 1;
	fi
	if [ ! -e "$1" ] ;then
		echo "check_directory_group() Error $1 do not exist"
		return 1;
	fi
	if [ -z "$2" ] ;then
		echo 'Error missing parameter #2 (group) for check_directory_group()'
		return 1;
	fi
	if [ -z "$3" ] ;then
		echo 'Error missing parameter #3 (path to the output) for check_directory_group()'
		return 1;
	fi
	if [ -z "$4" ] ;then
		echo 'Error missing parameter #4 (indent) for check_directory_group()'
		return 1;
	fi
	ADVICE="--advice $5"
	if [ -z "$5" ] ; then
		ADVICE=''
	fi
	find "$1" ! -group "$2" > "$3"
	RESULTAT=`cat "$3" | wc -l`
	if [ $RESULTAT -eq 0 ] ;then
		Display --indent $4 --text "Group of $1" --result OK --color GREEN
	else
		Display --indent $4 --text "$RESULTAT files have invalid group owning != $2 in $1" --result WARNING --color RED $ADVICE
	fi
}

################################################################################
################################################################################
#Check that a directory do not have right for the world
# Param #1 is the PATH to be checked
# Param #2 is the file that get output of this function
# Param #3 is the indent value for print info
# Param #4 is the advice

check_directory_others()
{
	if [ -z "$1" ] ;then
		echo 'Error missing parameter #1 (PATH) for check_directory_others()'
		return 1;
	fi
	if [ ! -e $1 ] ;then
		echo "check_directory_others() Error $1 do not exist"
		return 1;
	fi
	if [ -z "$2" ] ;then
		echo 'Error missing parameter #2 (path to the output) for check_directory_others()'
		return 1;
	fi
	if [ -z "$3" ] ;then
		echo 'Error missing parameter #3 (indent) for check_directory_others()'
		return 1;
	fi
	if [ -z "$4" ] ;then
		echo 'Error missing parameter #4 (advice) for check_directory_others()'
		return 1;
	fi
	find "$1"  ! -type l -perm $ORWX > $2
	RESULTAT=`cat $2 | wc -l`
	if [ $RESULTAT -eq 0 ] ;then
		Display --indent $3 --text "Rights of $1" --result OK --color GREEN
	else
		Display --indent $3 --text "$RESULTAT files have invalid others rights in $1" --result WARNING --color RED --advice $4
		add_correction "chmod -R $CORRECT_ORWX $1"
	fi

}
################################################################################
################################################################################
#Check dir
check_directory_writable_by_group()
{
	if [ -z "$1" ]
	then
		echo 'Error missing parameter #1 (PATH) for check_directory_writable_by_group()'
		return 1;
	fi
	if [ ! -e $1 ]
	then
		echo "check_directory_writable_by_group() Error $1 do not exist"
		return 1;
	fi
	if [ -z "$2" ]
	then
		echo 'Error missing parameter #2 (group) for check_directory_writable_by_group()'
		return 1;
	fi
	if [ -z "$3" ]
	then
		echo 'Error missing parameter #3 (path to the output) for check_directory_writable_by_group()'
		return 1;
	fi
	if [ -z "$4" ]
	then
		echo 'Error missing parameter #4 (indent) for check_directory_writable_by_group()'
		return 1;
	fi
	find "$1" ! -type l -perm $PERM_GW > $3
	RESULTAT=`cat $3 | wc -l`
	if [ $RESULTAT -eq 0 ]
	then
		Display --indent $4 --text "$2 cannot write $1" --result OK --color GREEN
	else
		Display --indent $4 --text "$2 can write $RESULTAT files in $1" --result WARNING --color RED --advice $5
	fi

}

################################################################################
################################################################################
prepare_kernel_config()
{
	if [ -e "${TEMPYASATDIR}/kernel_config" ] ;then
		rm "${TEMPYASATDIR}/kernel_config"
	fi
	#config can be found at /boot/config-`uname -r`
	if [ -e "/boot/config-`uname -r`" ] ;then
		Display --indent 2 --text "/boot/config-`uname -r`" --result FOUND --color GREEN
		cat "/boot/config-`uname -r`" > "${TEMPYASATDIR}/kernel_config"
	fi
	# if user give me the path to a .config, i wont read /proc/config.gz
	if [ -z ${YASAT_PATH_TO_KERNEL_CONFIG:-""} ]	;then
		YASAT_PATH_TO_KERNEL_CONFIG='/usr/src/linux/.config'
		if [ -e /proc/config.gz ] ;then
			Display --indent 2 --text "/proc/config.gz" --result FOUND --color GREEN
			zcat /proc/config.gz > ${TEMPYASATDIR}/kernel_config
		else
			if [ -e "${TEMPYASATDIR}/kernel_config" ] ;then
				#we have already found .config elsewhere
				Display --indent 2 --text "/proc/config.gz" --result NOTFOUND --color BLUE
			else
				Display --indent 2 --text "/proc/config.gz" --result NOTFOUND --color ORANGE --advice KERNEL_NO_CONFIG
			fi
		fi
	fi
	if [ ! -e "${TEMPYASATDIR}/kernel_config" ] ;then
		if [ -e "$YASAT_PATH_TO_KERNEL_CONFIG" ] ;then  
			Display --indent 2 --text "$YASAT_PATH_TO_KERNEL_CONFIG" --result FOUND --color GREEN
			cat "$YASAT_PATH_TO_KERNEL_CONFIG" > ${TEMPYASATDIR}/kernel_config
		else    
			Display --indent 2 --text "$YASAT_PATH_TO_KERNEL_CONFIG" --result NOTFOUND --color ORANGE --advice KERNEL_NO_CONFIG
		fi      
	fi      

}


################################################################################
################################################################################

prepare_apache_conf()
{
	if [ -z "$1" ]
	then
		echo 'Error missing parameter #1 (apache directory) for prepare_apache_conf()'
		return 1;
	fi
	if [ ! -d $1 ]
	then
		echo "prepare_apache_conf() Error $1 is not a directory"
		return 1;
	fi
	if [ -e "$TEMPYASATDIR/apache.conf" ] ;	then
		rm "$TEMPYASATDIR/apache.conf"
	fi
	if [ -e "$TEMPYASATDIR/apache.conf.found" ] ;	then
		rm "$TEMPYASATDIR/apache.conf.found"
	fi
	if [ -e "$1/apache2.conf" ] ; then
		grep -v '^[[:space:]]*#' $1/apache2.conf > "$TEMPYASATDIR/apache.conf"
		echo "$1/apache2.conf" >> "$TEMPYASATDIR/apache.conf.found"
	fi
	if [ -e "$1/httpd.conf" ] ; then
		grep -v '^[[:space:]]*#' $1/httpd.conf >> "$TEMPYASATDIR/apache.conf"
		echo "$1/httpd.conf" >> "$TEMPYASATDIR/apache.conf.found"
	fi
	if [ -e "$1/httpd2.conf" ] ;then
		grep -v '^[[:space:]]*#' $1/httpd2.conf >> "$TEMPYASATDIR/apache.conf"
		echo "$1/httpd2.conf" >> "$TEMPYASATDIR/apache.conf.found"
	fi

	if [ ! -e "$TEMPYASATDIR/apache.conf" ]
	then
		Display --indent 2 --text "I cannot find apache configuration" --result WARNING --color RED
		return 1;
	fi

	FindValueOf "$TEMPYASATDIR/apache.conf" "ServerRoot"
	if [ -z "$RESULTAT" ] ;	then
		Display --indent 2 --text "No ServerRoot found, defaulting to /etc/apache2" --result WARNING --color BLUE
		SERVERROOT='/etc/apache2'
	else
		SERVERROOT=`echo $RESULTAT | sed 's/^\"//' | sed 's/\"$//'`
	fi

	grep -i '^[[:space:]]*include' "$TEMPYASATDIR/apache.conf" | sed 's/^[[:space:]]*[a-zA-Z][a-zA-Z]*[[:space:]][[:space:]]*//g'  | sort | uniq |
	while read TMP_FILES
	do
#		TMP_FILES="`echo \"$line\" | sed 's/^[[:space:]]*include[[:space:]]*//gI'`"
#		echo "$TMP_FILES"
		#Check for relative files
		FIRST_CHAR=`echo $TMP_FILES | cut -b 1`
		if [ "$FIRST_CHAR" != "/" ];then
#			echo "Debug relative path"
			TMP_FILES="$SERVERROOT/$TMP_FILES"
		fi

		if [ -d "$TMP_FILES" ];then
			Debug "$TMP_FILES has no wildward"
			TMP_FILES="$TMP_FILES/*"
		fi
		Debug "Add $TMP_FILES"
		echo "$TMP_FILES" >> "$TEMPYASATDIR/apache.conf.found"
		#-s for be sure that on a minimal config with no modules/*.conf no errors would be printed
		grep -vsh '^[[:space:]]*#' $TMP_FILES > "$TEMPYASATDIR/apache.conf.tmp"
		grep -vsh '^[[:space:]]*#' $TMP_FILES >> "$TEMPYASATDIR/apache.conf"
		#check recursivly for additional includes
		grep -ih '^[[:space:]]*include' "$TEMPYASATDIR/apache.conf.tmp" | sed 's/^[[:space:]]*[a-zA-Z][a-zA-Z]*[[:space:]][[:space:]]*//g' | sort | uniq |
		while read TMP_FILESS
		do
#			echo "$TMP_FILESS"
			grep -vh '^[[:space:]]*#' $TMP_FILESS >> "$TEMPYASATDIR/apache.conf"
		done

	done
}


################################################################################
################################################################################
prepare_bind_conf()
{
	if [ -z "$1" ]
	then
		echo 'Error missing parameter #1 (named/bind directory) for prepare_bind_conf()'
		return 1;
	fi
	if [ ! -d $1 ]
	then
		echo "prepare_bind_conf() Error $1 is not a directory"
		return 1;
	fi
	if [ -e "$TEMPYASATDIR/named.conf" ]
	then
		rm "$TEMPYASATDIR/named.conf"
	fi
	if [ -e "$1/named.conf" ]
	then
		grep -v '^[[:space:]]*#' $1/named.conf | grep -v '^[[:space:]]*$' | grep -v '^/'> "$TEMPYASATDIR/named.conf"
	fi

	if [ ! -e "$TEMPYASATDIR/named.conf" ]
	then
		Display --indent 2 --text "I cannot find bind configuration" --result WARNING --color RED
		return 1;
	fi

	grep -i '^[[:space:]]*include' "$TEMPYASATDIR/named.conf" | sed 's/^[[:space:]]*[a-zA-Z][a-zA-Z]*[[:space:]][[:space:]]*//g' | sed 's/";*//g' | sort | uniq |
	while read TMP_FILES
	do
		#Check for relative files
		FIRST_CHAR=`echo $TMP_FILES | cut -b 1`
		if [ "$FIRST_CHAR" != "/" ]
		then
#			echo "Debug relative path"
			TMP_FILES="$1/$TMP_FILES"
		fi

		if [ -d "$TMP_FILES" ]
		then
			Debug "$TMP_FILES has no wildward"
			TMP_FILES="$TMP_FILES/*"
		fi
		Debug "Add $TMP_FILES"
		grep -vh '^[[:space:]]*#' $TMP_FILES > "$TEMPYASATDIR/named.conf.tmp"
		grep -vh '^[[:space:]]*#' $TMP_FILES >> "$TEMPYASATDIR/named.conf"
		#check recursivly for additional includes
		grep -ih '^[[:space:]]*include' "$TEMPYASATDIR/named.conf.tmp" | sed 's/^[[:space:]]*[a-zA-Z][a-zA-Z]*[[:space:]][[:space:]]*//g' | sed 's/";*//g' | sort | uniq |
		while read TMP_FILESS
		do
#			echo "$TMP_FILESS"
			grep -vh '^[[:space:]]*#' $TMP_FILESS | grep -v '^[[:space:]]*$' | grep -v '^/'>> "$TEMPYASATDIR/named.conf"
		done

	done
}


################################################################################
################################################################################
# with a initial config file, generate a parseable config file
# add all files with include
# similar to prepare_apache_conf
prepare_generic_conf()
{
	if [ -z "$1" ]
	then
		echo 'Error missing parameter #1 (initial config file) for prepare_generic_conf()'
		return 1;
	fi
	if [ ! -e $1 ]
	then
		echo "prepare_generic_conf() Error $1 is not a config file"
		return 1;
	fi
	if [ -z "$2" ]
	then
		echo "prepare_generic_conf() Missing parameter #2 (output file)"
		return 1;
	fi

	if [ -e "$2" ]
	then
		cp "$2" "$2.bak"
		rm "$2"
	fi
	grep -v '^[[:space:]]*#' $1 | grep -v '^[[:space:]]*$' | grep -v '^;' > "$2"

	if [ ! -e "$2" ]
	then
		Display --indent 2 --text "I cannot find output configuration" --result WARNING --color RED
		return 1;
	fi

	grep -i '^[[:space:]]*include' "$2" | sed 's/^[[:space:]]*[a-zA-Z][a-zA-Z]*[[:space:]][[:space:]]*//g' | sed 's/";*//g' | sort | uniq |
	while read TMP_FILES
	do
		#Check for relative files
		FIRST_CHAR=`echo $TMP_FILES | cut -b 1`
		if [ "$FIRST_CHAR" != "/" ]
		then
#			echo "Debug relative path"
			TMP_FILES="$1/$TMP_FILES"
		fi

		if [ -d "$TMP_FILES" ]
		then
			Debug "$TMP_FILES has no wildward"
			TMP_FILES="$TMP_FILES/*"
		fi
		Debug "Add $TMP_FILES"
		grep -vh '^[[:space:]]*#' $TMP_FILES > "$2.tmp"
		grep -vh '^[[:space:]]*#' $TMP_FILES >> "$2"
		#check recursivly for additional includes
		grep -ih '^[[:space:]]*include' "$2.tmp" | sed 's/^[[:space:]]*[a-zA-Z][a-zA-Z]*[[:space:]][[:space:]]*//g' | sed 's/";*//g' | sort | uniq |
		while read TMP_FILESS
		do
#			echo "$TMP_FILESS"
			grep -vh '^[[:space:]]*#' $TMP_FILESS | grep -v '^[[:space:]]*$' | grep -v '^/'>> "$2"
		done

	done
}


################################################################################
################################################################################
#return the options of the partition
#we could do the same with mount but bsd do not print the same infos

check_partition()
{
if [ -z "$1" ] ; then
	echo "ERROR check_partition() Missing arg #1 (mount point)"
	return 1;
fi
	RESULTAT=''
	EL_MOUNT=`grep -v '^#' /etc/fstab |grep "$1/*[[:space:]]"`
	if [ -z "$EL_MOUNT" ] ; then
		Display --indent 2 --text "$1 is not on a separate partition" --result NOTFOUND --color RED --advice PARTITION_SEPARATE_PART
		return 1;
	fi
	RESULTAT=`echo $EL_MOUNT | sed 's/[[:space:]]/ /g' | cut -d\  -f4`
	Display --indent 2 --text "$1 is on a separate partition" --result FOUND --color GREEN
}

################################################################################
################################################################################
#
# must produce a 4 digits results
get_full_right()
{
if [ "$1x" = "x" ]
then
	echo "ERROR get_right() missing parameter #1"
	return 1;
fi
if [ ! -e "$1" ]
then
	echo "ERROR $1 do not exists"
	return 1;
fi

if [ "$OS" = "FreeBSD" ]
then
	RESULTAT=`stat -f %Mp%Lp $1`
else
	RESULTAT=`stat --format=%a $1`
fi

}
################################################################################
################################################################################
# get the right of a file
# must produce a 3 digits results
get_simple_right()
{
RESULTAT='Error'
if [ "$1x" = "x" ]
then
	echo "ERROR get_simple_right() missing parameter #1 (file to be stated)"
	return 1;
fi
if [ ! -e "$1" ]
then
	echo "ERROR $1 do not exists"
	return 1;
fi

if [ "$OS" = "FreeBSD" ]
then
	RESULTAT=`stat -f %Lp $1`
else
	RESULTAT=`stat --format=%a $1`
fi

}


################################################################################
################################################################################
#For the fun
draw_apache_tree()
{
if [ "$1x" = "x" ]
then
	echo "ERROR check_partition() missing parameter #1"
	return 1;
fi
NUMINDENT=0

echo ''
echo "Draw apache tree (still in development)"
echo ''

cat $1 |
while read line
do
#	echo $line
	if [ ! -z "`echo $line | grep -i '^VHOST'`" ]
	then
		echo "|-V- $line" | sed 's/VHOST=//g'
		NUMINDENT=2
	fi
	if [ ! -z "`echo $line | grep -i '^ENDHOST'`" ]
	then
		echo "|"
		NUMINDENT=0
	fi
	if [ ! -z "`echo $line | grep -i '^ALIAS'`" ]
	then
		if [ $NUMINDENT -ge 2 ]
		then
			echo "|   |-A- $line" | sed 's/ALIAS=//g'
		else
			echo "|-A- $line" | sed 's/ALIAS=//g'
		fi
	fi
	if [ ! -z "`echo $line | grep -i '^PASSWORD'`" ]
	then
		if [ $NUMINDENT -ge 2 ]
		then
			echo '|   |   |--- PASSWORD'
		else
			echo '|   |--- PASSWORD'
		fi
	fi
	if [ ! -z "`echo $line | grep -i '^DENYFROMALL'`" ]
	then
		if [ $NUMINDENT -ge 2 ]
		then
			echo '|   |   |--- DENYFROMALL'
		else
			echo '|   |--- DENYFROMALL'
		fi
	fi
	if [ ! -z "`echo $line | grep -i '^AUTHFILE'`" ]
	then
		if [ $NUMINDENT -ge 2 ]
		then
			echo "|   |   |-P- $line"  | sed 's/AUTHFILE=//g'
		else
			echo "|   |-P- $line" | sed 's/AUTHFILE=//g'
		fi
	fi
	if [ ! -z "`echo $line | grep -i '^DIRECTORY'`" ]
	then
		if [ $NUMINDENT -ge 2 ]
		then
			echo "|   |-D- $line" | sed 's/DIRECTORY=//g'
		else
			echo "|-D- $line" | sed 's/DIRECTORY=//g'
		fi
	fi
	if [ ! -z "`echo $line | grep -i '^LOCATION'`" ]
	then
		if [ $NUMINDENT -ge 2 ]
		then
			echo "|   |-L- $line" | sed 's/LOCATION=//g'
		else
			echo "|-L- $line" | sed 's/LOCATION=//g'
		fi
	fi
	if [ ! -z "`echo $line | grep -i '^HLOC'`" ]
	then
		if [ $NUMINDENT -ge 2 ]
		then
			echo "|   |-H- $line" | sed 's/HLOC=//g'
		else
			echo "|-H- $line" | sed 's/HLOC=//g'
		fi
	fi
	if [ ! -z "`echo $line | grep -i '^PROXY'`" ]
	then
		if [ $NUMINDENT -ge 2 ]
		then
			echo "|   |-Pr- $line" | sed 's/PROXY=//g'
		else
			echo "|-Pr- $line" | sed 's/PROXY=//g'
		fi
	fi
	if [ ! -z "`echo $line | grep -i '^JKMOUNT'`" ]
	then
		if [ $NUMINDENT -ge 2 ]
		then
			echo "|   |-J- $line" | sed 's/JKMOUNT=//g'
		else
			echo "|-J- $line" | sed 's/JKMOUNT=//g'
		fi
	fi
	if [ ! -z "`echo $line | grep -i '^SERVERNAME'`" ]
	then
		if [ $NUMINDENT -ge 2 ]
		then
			echo "|   |-SN- $line" | sed 's/SERVERNAME=//g'
		else
			echo "|-SN- $line" | sed 's/SERVERNAME=//g'
		fi
	fi
	if [ ! -z "`echo $line | grep -i '^DEFLATE'`" ] ; then
		if [ $NUMINDENT -ge 2 ] ; then
			echo "|   |-mD- $line" | sed 's/DEFLATE=//g'
		else
			echo "|-mD- $line" | sed 's/DEFLATE=//g'
		fi
	fi
	if [ ! -z "`echo $line | grep -i '^PHP_ADMIN_VALUE'`" ] ; then
		if [ $NUMINDENT -ge 2 ] ; then
			echo "|   |-PHP- $line" | sed 's/PHP_ADMIN_VALUE=//g'
		else
			echo "|-PHP- $line" | sed 's/PHP_ADMIN_VALUE=//g'
		fi
	fi
done
echo ''
echo '-D- Directory -L- Location -V- vhost -A- alias -J- JKmount -mD- ModDeflate -PHP- PHP specific value'
}


################################################################################
################################################################################
#extract path from <directive value>
get_path_from_apache_directives()
{
if [ -z "$1" ]
then
	echo "Missing parameter #1 (line to proceed) for get_path_from_apache_directives()"
	return 1;
fi
#echo "->$1"
export RESULTAT=`echo $1 | sed 's/^[[:space:]]*<[[:space:]]*[a-zA-Z0-9][a-zA-Z0-9]*[[:space:]]*//g'| sed 's/[[:space:]]*>.*//g' | cut -d\" -f2`
#echo $1 | sed 's/^[[:space:]]*<[[:space:]]*//g'
#export $RESULTAT
return 0;
}

################################################################################
################################################################################
#extract path from <directive value>
armageddon()
{
    echo "EXit via Ctrl-C"
    exit 1;
}

################################################################################
################################################################################
Do_the_host_is_a_virtual_machine()
{
HOST_IS_VIRTUAL_MACHINE=0
if [ "$OS_TYPE" = 'Linux' ] ;then
	CPUMODEL="`cat /proc/cpuinfo |grep QEMU`"
	if [ ! -z "$CPUMODEL" ] ;then
		export HOST_IS_VIRTUAL_MACHINE=1
	else
		export HOST_IS_VIRTUAL_MACHINE=0
	fi
	return 0;
fi
if [ "$OS_TYPE" = 'BSD' ] ;then
 	CPUMODEL="`sysctl -a | grep -i 'hw.model' |grep QEMU`"
	if [ ! -z "$CPUMODEL" ] ;then
		export HOST_IS_VIRTUAL_MACHINE=1
	else
		export HOST_IS_VIRTUAL_MACHINE=0
	fi
	return 0;
fi
#unrecognized
export HOST_IS_VIRTUAL_MACHINE=0
}

################################################################################
################################################################################
# Check if a program is installed via the package manager or at hand
#
# $1 is the package to be searched
#
# RESULTAT is yes or no or NOTIMPLEMENTED or ERROR
# RESULTAT_VERSION is the version number
# use LIST_PKG for finding package, (rpm, dpkg, emerge)
Is_installed_via_package_manager()
{
	export RESULTAT='ERROR'
	if [ -z "$1" ] ;then
		echo "ERROR Is_installed_via_package_manager() missing parameter #1"
		return 1;
	fi
	if [ "$LIST_PKG" = "dpkg" -o "$LIST_PKG" = "apt-get" ] ;then
		PKGLIST="`dpkg -l |grep ^ii |grep -i $1`"
		if [ -z "$PKGLIST" ] ;then
			export RESULTAT='no'
		else
			export RESULTAT='yes'
		fi
		return 0;
	fi
	if [ "$LIST_PKG" = "rpm" ] ;then
		PKGLIST="`rpm -qa |grep ^$1`"
		if [ -z "$PKGLIST" ] ;then
			export RESULTAT='no'
		else
			export RESULTAT='yes'
		fi
		return 0;
	fi
	if [ "$LIST_PKG" = "emerge" ] ;then
		#TODO could be better
		PKGLIST="`equery -C -q l $1`"
		if [ -z "$PKGLIST" ] ;then
			export RESULTAT='no'
		else
			export RESULTAT='yes'
		fi
		return 0;
	fi
	if [ "$LIST_PKG" = "pacman" ] ;then
		PKGLIST="`pacman -Q | grep ^$1`"
		if [ -z "$PKGLIST" ] ;then
			export RESULTAT='no'
		else
			export RESULTAT='yes'
		fi
		return 0;
	fi
	#TODO pkg_ with pkg_info
	echo "Is_installed_via_package_manager() $LIST_PKG NOTIMPLEMENTED"
	export RESULTAT='NOTIMPLEMENTED'
	return 1;
}
################################################################################
################################################################################
# Check if a program is auto started
# $1 is the package to be checked
# RESULTAT is the result yes or no or NOTIMPLEMENTED or ERROR
# RESULTAT_VERSION is the version number
Check_auto_start()
{
	export RESULTAT='ERROR'
	if [ -z "$1" ]
	then
		echo "ERROR Is_installed_via_package_manager() missing parameter #1"
		return 1;
	fi
	if [ "$LINUX_VERSION" = 'Red Hat' -o "$LINUX_VERSION" = 'Centos' ]
	then
		chkconfig $1 > /dev/null
		if [ $? -eq 0 ]
		then
			export RESULTAT='yes'
		else
			export RESULTAT='no'
		fi
		return 0;
	fi
	if [ "$LINUX_VERSION" = "Debian" ]
	then
		#could be better
		if [ ! -z "`find /etc/rc* |grep -i $1`" ]
		then
			export RESULTAT='yes'
		else
			export RESULTAT='no'
		fi
		return 0;
	fi
	if [ "$LINUX_VERSION" = "Gentoo" ] ; then
		RUNLEVEL="`rc-update show 2>> $ERROR_OUTPUT_FILE | grep $1 `"
		if [ $? -ne 0 ] ; then
			export RESULTAT='ERROR'
			return 1;
		fi
		if [ -z "$RUNLEVEL" ] ;	then
			export RESULTAT='no'
		else
			export RESULTAT='yes'
		fi
		return 0;
	fi
	export RESULAT='NOTIMPLEMENTED'
	return 1;
}

################################################################################
################################################################################
Check_for_update()
{
RET=0
wget -nv "http://yasat.sourceforge.net/get_last_yasat_version.php?current=$YASAT_VERSION" -O latest
if [ $? -ne 0 -o ! -e latest ];then
	echo "Error with wget"
	rm latest
	exit 2
fi
LAST_VERSION="`cat latest`"
echo "You have yasat version $YASAT_VERSION and the latest is $LAST_VERSION"

if [ "$YASAT_VERSION" -eq "$LAST_VERSION" ];then
	echo "You have already the latest version of YASAT"
fi
if [ "$YASAT_VERSION" -lt "$LAST_VERSION" ];then
	echo "A new version is available at http://yasat.sourceforge.net/"
	RET=1
fi

rm latest
exit $RET
}
################################################################################
################################################################################
send_support()
{
. ${YASAT_ROOT}/osdetection
RET=0
SYSTEME="${LINUX_VERSION}${OS}$OS_FULLNAME"
wget -nv "http://yasat.sourceforge.net/get_last_yasat_version.php?current=$YASAT_VERSION&systeme=$SYSTEME" -O latest
if [ $? -ne 0 -o ! -e latest ] ;then
	echo "Error with wget"
	rm latest
	exit 2
fi
LAST_VERSION="`cat latest`"
echo "You have yasat version $YASAT_VERSION and the latest is $LAST_VERSION"

if [ "$YASAT_VERSION" -eq "$LAST_VERSION" ];then
	echo "You have already the latest version of YASAT"
fi
if [ "$YASAT_VERSION" -lt "$LAST_VERSION" ];then
	echo "A new version is available at http://yasat.sourceforge.net/"
	RET=1
fi

rm latest
exit $RET
}
################################################################################
################################################################################
#Try to identify which technology is behind a vhost or a directory
#example PHP mod_perl JAVA/JK
# for the moment test a very simple case:)
#
# param $1 is the directory to scan
# param $2 (optional)
identify_web_tech_in_dir()
{
	WEBTECH='unknown'
	if [ -z "$1" ] ; then
		echo "ERROR identify_web_tech_dir missing parameter #1"
		return 1;
	fi
	#check if $1 contain a *
	if [ ! -z "`echo $1 |grep '*'`" ] ; then
		return ;
	fi
	if [ $1 = '/' ] ; then
		return ;
	fi
	if [ -e "$1/index.php" ] ; then
		echo "PHP"
		export WEBTECH="PHP"
		return ;
	fi
	if [ $# -ge 2 ] ; then
		if [ "$2" = "recursive" ] ; then
			if [ ! -z "`find $1 -maxdepth 2 -type f |grep 'php$'`" ] ; then
				export WEBTECH="PHP"
				return ;
			fi
		fi
	fi

}

################################################################################
################################################################################
qa_test()
{
	if [ "$1" != "$2" ] ; then
		echo "BAD got $1 not $2"
	else
		echo "GOOD (result is $1)"
	fi
}
################################################################################
################################################################################
# find witch file have a specific directive
find_file_with_directive()
{
	export RES_FILE_WITH_DIRECTIVE='/tmp/nonexistent'
	if [ -z "$1" ] ; then
		echo 'Error missing parameter #1 directory for find_file_with_directive()'
		return 1;
	fi
	if [ -z "$2" ] ; then
		echo 'Error missing parameter #2 directive for find_file_with_directive()'
		return 1;
	fi
	RES_FILE_WITH_DIRECTIVE="`grep -rli $2 $1 | head -n 1`"
	#manpage said that -l return only one line but it seems false
}
################################################################################
################################################################################
#
add_correction()
{
	echo "$1" >> "$CORRECT_FILE"
}
################################################################################
################################################################################
# list all test comment. In the future we could list by reference id (by CCE ID for example)
list_all_yasat_test() {
	grep -h '#YASAT_TEST' ${PLUGINS_REP}/*.test | sed 's/^[[:space:]]*//g'
}
################################################################################
################################################################################
#check_value value_tested value_wanted bad_if_empty? text colour advice
check_value() {
	if [ -z "$2" ] ; then
		echo 'Error missing parameter #2 value_wanted for check_value()'
		return 1;
	fi
	if [ -z "$3" ] ; then
		echo 'Error missing parameter #3 bad_if_empty? for check_value()'
		return 1;
	fi
	if [ -z "$4" ] ; then
		echo 'Error missing parameter #4 text for check_value()'
		return 1;
	fi
	if [ -z "$5" ] ; then
		echo 'Error missing parameter #5 colour for check_value()'
		return 1;
	fi
	if [ -z "$6" ] ; then
		echo 'Error missing parameter #5 advice for check_value()'
		return 1;
	fi
	if [ -z "$1" ] ; then
		if [ "$3" = 'true' ] ; then
			Display --indent 2 --text "$4" --result "NOTFOUND" --color $5 --advice $6
		else
			Display --indent 2 --text "$4" --result "NOTFOUND" --color GREEN
		fi
		return 0;
	fi
	if [ "$1" != "$2" ]; then
		Display --indent 2 --text "$4" --result "$1" --color $5 --advice $6
	else
		Display --indent 2 --text "$4" --result "$1" --color GREEN
	fi
}

################################################################################
################################################################################
#get the value after i"$1" in a line
#used for apache_vhosts, we assume $1 is present
get_value_in_string() {
	if [ -z "$1" ] ; then
		echo 'Error missing parameter #1 value_wanted for get_value_in_string()'
		return 1;
	fi
	if [ -z "$2" ] ; then
		echo 'Error missing parameter #2 string to be seeked for get_value_in_string()'
		return 1;
	fi
	export RESULTAT="`echo $2 | sed 's/^[[:space:]]*//' | sed 's,#.*,,' | sed 's,[[:space:]][[:space:]]*, ,g' | cut -d\  -f2`"
}
