#!/bin/bash
#
# Copyright (c) Members of the EGEE Collaboration. 2004-2007.
# See http://public.eu-egee.org/partners/ for details on 
# the copyright holders.
# For license conditions see the license file or
# http://www.apache.org/licenses/LICENSE-2.0
#
# Authors: Akos Frohner <Akos.Frohner@cern.ch>

PACKAGENAME='glite-data-hydra-service'

##########################################################################
# common part
##########################################################################

USAGE="$0 [--dryrun] [--withpass=<password>] [--values config_values_filename] [--configdir config_directory]"

# the text to be printed at the end
cleanuptext=$cleanuptext"# you can clean up using the following commands\n"

TEMP=$(getopt -o hdw: --long help,dryrun,withpass:,values:,configdir: -- "$@")
eval set -- "$TEMP"

while true; do
    case "$1" in
        -d|--dryrun)
            DRYRUN='echo Info:'
            shift
            ;;
        -w|--withpass)
            shift
            WITHPASS="--pass=$1"
            shift
            ;;
        --values)
            shift
            CONFIGFILE="$1"
            shift
            ;;
        --configdir)
            shift
            CONFIGDIR="$1"
            shift
            ;;
        -h|--help)
            echo $USAGE
            exit
            ;;
        --)
            # end of options
            shift
            break
            ;;
    esac
done

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

GLITE_LOCATION=${GLITE_LOCATION:-/opt/glite}

if [ ! -d "$GLITE_LOCATION" ]; then
    echo "Error: '$GLITE_LOCATION' does not exsits." >&2
    echo "Error: Please specify GLITE_LOCATION!" >&2
    echo $USAGE >&2
    exit 1
fi

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

CONFIGFILE=${CONFIGFILE:-$GLITE_LOCATION/yaim/etc/site.info}

if [ ! -f "$CONFIGFILE" ]; then
    echo "Error: Please specify the configuration values file!" >&2
    echo " (e.g. site.info)" >&2
    echo $USAGE >&2
    exit 1
fi

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

CONFIGDIR=${CONFIGDIR:-$GLITE_LOCATION/etc/$PACKAGENAME}

if [ ! -d "$CONFIGDIR" ]; then
    echo "Error: Please specify the configuration directory!" >&2
    echo " (e.g. /opt/glite/etc/$PACKAGENAME)" >&2
    echo $USAGE >&2
    exit 1
fi

#################################################################
# looking for the Tomcat directory

if [ -z "$CATALINA_BASE" ]; then
    # system default
    [ -r /etc/tomcat5/tomcat5.conf ] && source /etc/tomcat5/tomcat5.conf
    # RedHat settings
    [ -r /etc/sysconfig/tomcat5 ] && source /etc/sysconfig/tomcat5
    # Debian settings
    [ -r /etc/default/tomcat5 ] && source /etc/default/tomcat5
    # test settings
    [ -n "$TOMCAT5_CONF" ] && source "$TOMCAT5_CONF"
fi

# Find Tomcat's webapps dir
for TOMCAT_CONF in ${CATALINA_HOME}/conf /var/tomcat5/conf /var/lib/tomcat5/conf /etc/tomcat5; do
    if [ -r ${TOMCAT_CONF}/server.xml ]; then
        break
    fi
done
if [ ! -r "${TOMCAT_CONF}/server.xml" ]; then
    echo "Error: could not find Tomcat5 configuration directory!" >&2
    exit 2
fi

#################################################################
# other defaults

DOCBASE=${DOCBASE:-$GLITE_LOCATION/share/java/hydra-service.war}
LOG4JCONFIG=${LOG4JCONFIG:-$GLITE_LOCATION/etc/glite-data-hydra-service/log4j.properties}
VOMSDIR=${VOMSDIR:-/etc/grid-security/vomsdir}
HOSTNAME=${HOSTNAME:-$(hostname --fqdn)}
DBHOSTNAME=${HYDRA_DB_HOSTNAME:-$HOSTNAME}

source $CONFIGFILE

for instance in $HYDRA_INSTANCES; do
    echo ""
    echo "Info: Configuring '$instance' instance..."
    ref_DBNAME="HYDRA_DBNAME_$instance"
    ref_DBUSER="HYDRA_DBUSER_$instance"
    ref_DBPASSWORD="HYDRA_DBPASSWORD_$instance"
    ref_CREATE="HYDRA_CREATE_$instance"
    ref_ADMIN="HYDRA_ADMIN_$instance"
    context_name="${TOMCAT_CONF}/Catalina/localhost/$instance#glite-data-hydra-service.xml"
    log4j_name="$CONFIGDIR/log4j.$instance.properties"

    # sanity checks
    echo "${!ref_DBPASSWORD}" | grep -q '@'
    if [ $? -eq 0 ]; then
        echo "Error: DB password for instance '$instance' cannot contain the '@' character!" >&2
        exit 5
    fi
    # DB password shall be readable only for tomcat.
    if [ -n "$TOMCAT_USER" ]; then
        $DRYRUN touch "$context_name"
        $DRYRUN chmod 0600 "$context_name"
        $DRYRUN chown $TOMCAT_USER "$context_name"
    fi

    echo "Info: generating the log4j.properties file"
    sedscript="s,@INSTANCE@,$instance,;"
    if [ -n "$DRYRUN" ]; then
        $DRYRUN $sedscript
    else
        sed -e "$sedscript" $CONFIGDIR/log4j.template.properties >"$log4j_name"
        cleanuptext=$cleanuptext"    rm '$log4j_name'\n"
    fi

    echo "Info: generating the Tomcat service context XML file."
    sedscript="s,@DOCBASE@,$DOCBASE,; s,@LOG4JCONFIG@,$log4j_name,; s,@HOSTNAME@,$HOSTNAME,; s/@DBUSER@/${!ref_DBUSER}/; s/@DBPASSWORD@/${!ref_DBPASSWORD}/; s/@DBNAME@/${!ref_DBNAME}/; s,@CREATE@,${!ref_CREATE},; s,@ADMIN@,${!ref_ADMIN},; s,@VOMSDIR@,$VOMSDIR,;"
    if [ -n "$DRYRUN" ]; then
        $DRYRUN $sedscript
    else
        sed -e "$sedscript" $CONFIGDIR/context.template.xml >"$context_name"
        cleanuptext=$cleanuptext"    rm '$context_name'\n"
    fi

    # check if the schema already exists
    schema_version=''
    if [ -n "$DRYRUN" ]; then
        $DRYRUN mysql -u ${!ref_DBUSER} -p${!ref_DBPASSWORD} -D ${!ref_DBNAME} -BN -e "source $CONFIGDIR/schema/mysql/mysql-get-version.sql;"
    else
        schema_version=$(mysql -u ${!ref_DBUSER} -p${!ref_DBPASSWORD} -D ${!ref_DBNAME} -BN -e "source $CONFIGDIR/schema/mysql/mysql-get-version.sql;" 2>/dev/null)
        if [ $? -ne 0 ]; then
            schema_version=''
        fi
    fi

    if [ -z "$schema_version" ]; then
        echo "Info: creating the DB user."
        $DRYRUN mysql -u root -h $DBHOSTNAME $WITHPASS -e "CREATE DATABASE ${!ref_DBNAME};
        grant ALL PRIVILEGES on ${!ref_DBNAME}.* to ${!ref_DBUSER} identified by '${!ref_DBPASSWORD}';
        grant ALL PRIVILEGES on ${!ref_DBNAME}.* to ${!ref_DBUSER}@'$HOSTNAME' identified by '${!ref_DBPASSWORD}';
        grant ALL PRIVILEGES on ${!ref_DBNAME}.* to ${!ref_DBUSER}@localhost identified by '${!ref_DBPASSWORD}';
        flush privileges;"
        if [ $? -ne 0 ]; then
            echo "Error: could not create the DB user!" >&2
            exit 5
        fi
        cleanuptext=$cleanuptext"      mysql -u root $WITHPASS -e 'DROP DATABASE ${!ref_DBNAME};'\n"
        
        echo "Info: loading the schema."
        $DRYRUN mysql -u ${!ref_DBUSER} -p${!ref_DBPASSWORD} -D ${!ref_DBNAME} -e "source $CONFIGDIR/schema/mysql/mysql-schema.sql"
        if [ $? -ne 0 ]; then
            echo "Error: could not load the DB schema!" >&2
            exit 5
        fi
    elif [ "1.1.0" = "$schema_version" ]; then
        echo "Info: upgrading the schema from v1.1.0 to v1.2.0 on instance '$instance'"
        $DRYRUN mysql -u ${!ref_DBUSER} -p${!ref_DBPASSWORD} -D ${!ref_DBNAME} -e "source $CONFIGDIR/schema/mysql/mysql-upgrade-1.1.0-1.2.0.sql"
        if [ $? -ne 0 ]; then
            echo "Error: could not upgrade the database!" >&2
            exit 5
        fi
    elif [ "1.2.0" = "$schema_version" ]; then
        echo "Info: shcema is already loaded."
    else
        echo "Error: unknown schema version: $schema_version" >&2
        exit 5
    fi
done

#################################################################
# print_cleanup 
unconfigure="${CONFIGDIR}/unconfigure"
cleanuptext=$cleanuptext"    rm $unconfigure\n"
echo "Info: you can clean up by running '$unconfigure'"
# there is the DB password in this file, should be protected
touch $unconfigure
chmod 0700 $unconfigure
echo -e "#!/bin/sh\n# this was generated by $0\n" >>$unconfigure
echo -e $cleanuptext >>$unconfigure

