#! /bin/bash
#set -x

function usage()
{
    echo
    echo "usage : test_clean [-d DIRECTORY] -m MYSQL USER -p MYSQL PWD"
    echo

    exit 0
}

while getopts ":d:m:p:h" opt; do
    case $opt in
	d  ) directory=$OPTARG;;
 	m  ) mysql_user=$OPTARG;;
	p  ) mysql_pwd=$OPTARG;;
	h  ) usage;;
        \? ) usage
    esac
done

# check options

if test -z $mysql_user; then
    echo -e "\nERROR : mysql user not provided.\n"
    exit 1
fi

if test -z $mysql_pwd; then
    echo -e "\nERROR : password of mysql user not provided.\n"
    exit 1
fi

# check GLITE_LOCATION is set

GLITE_LOCATION=${GLITE_LOCATION}
if [ "${GLITE_LOCATION}" = "" ]; then
    echo "\$GLITE_LOCATION is empty, default to /opt/glite."
    GLITE_LOCATION=/opt/glite
else echo "\$GLITE_LOCATION is $GLITE_LOCATION."
fi
if ! test -d $GLITE_LOCATION; then
    echo -e "\nERROR : \$GLITE_LOCATION doesn't exists. \n" 
    exit 1;
fi
if ! test -w $GLITE_LOCATION; then
    echo -e "\nERROR : \$GLITE_LOCATION is not writable. \n"    
    exit 1;
fi

if [ "$directory" == "/etc" ] ; then
    echo -e "\nERROR : won't remove /etc/grid-security.\n"
    exit 1
fi

directory=${directory:-$GLITE_LOCATION/etc}

if ! test -e $directory/grid-security/vomses; then
    echo -e "\nERROR : configuration file not found, maybe $directory is not the installation dir.\n"
    exit 1
fi

let n=$(($(wc -l < $directory/grid-security/vomses)))

echo -ne "Stopping the vos  ...  "

let i=$((n))
while [ $i -gt 0 ] ; do

    if ! $GLITE_LOCATION/etc/init.d/voms stop test$i > /dev/null; then
	echo -e "\nERROR : error stopping vo test$i.\n"
	exit 1;
    fi
    
    let i=$i-1 

done

echo "Ok"

echo -ne "Removing test VOs  ...  "

while [ $n -gt 0 ] ; do

    if ! rm -rf $GLITE_LOCATION/etc/voms/"test"$n &> /dev/null; then
	echo -e "\nERROR : unable to remove conf directory $GLITE_LOCATION/opt/etc/voms/test.\n"
    fi

    if ! rm -rf $GLITE_LOCATION/var/log/voms."test"$n &> /dev/null; then
	echo -e "\nERROR : unable to remove log file $GLITE_LOCATION/opt/var/log.\n"
    fi

    sql=test_db$n
    if ! mysql -u root -ppwd -e "DROP DATABASE $sql"; then
	echo -e "\nERROR : unable to remove test database\n"
    fi

    let n=$n-1 

done

echo "Ok"

echo -ne "Removing CA  ...  "

rm -rf $directory/grid-security
rm -rf $directory/tarball.tar.gz

echo "Ok"
