#!/bin/sh
#
# Copyright (c) Members of the EGEE Collaboration. 2006-2009.
# See http://www.eu-egee.org/partners/ for details on the copyright holders.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
#set -x
RES_COL=40
MOVE_TO_COL="echo -en \\033[${RES_COL}G"
SETCOLOR_SUCCESS="echo -en \\033[1;32m"
SETCOLOR_FAILURE="echo -en \\033[1;31m"
SETCOLOR_WARNING="echo -en \\033[1;33m"
SETCOLOR_NORMAL="echo -en \\033[0;39m"

echo_success() {
  $MOVE_TO_COL
  echo -n "[  "
  $SETCOLOR_SUCCESS
  echo -n $1
  $SETCOLOR_NORMAL
  echo "  ]"
}

echo_failure() {
  $MOVE_TO_COL
  echo -n "[  "
  $SETCOLOR_FAILURE
  echo -n $1
  $SETCOLOR_NORMAL
  echo "  ]"
}

function test_vo {

	local voname="$1"
	set -e
	voms-admin --vo $voname get-vo-name 2>&1 >/dev/null
	retval=$?
   
	if [ $retval -eq 2 ]; then
		echo_failure "Network error: Tomcat is down."
   		return 1
	fi
   	
	if [ $retval -eq 3 ]; then
		echo_failure "SOAP error: VO is not active."
   		return 1
	fi
   
	if [ $retval -eq 1 ]; then
		echo_failure "Service error"
   		return 1
	fi
   	
	if [ $retval -ne 0 ]; then
		echo_failure Failure
		return 1
	fi
   
   echo_success OK
   return 0
}

vos=            # Space-separated list of VOs
function get_vos {
	source /etc/sysconfig/voms-admin
    if [ -d "${CONF_DIR}" ]; then
        for d in "${CONF_DIR}"/*; do
       if [ -r "$d/voms.database.properties" ]; then
       		vos="$vos `basename $d`"
       fi
   done
   all_vos=yes
    else 
        echo "It seems you don't have any VOs configured yet."
        exit 1
    fi
}


get_vos;

result=0

for vo in $vos; do
    echo -n "Testing $vo: "

    if test_vo $vo; then
   :
    else
   result=1
    fi
done

exit $result
