#!/bin/sh

# 
# Copyright 1999-2006 University of Chicago
# 
# 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.
# 


PACKAGE=@PACKAGE@
VERSION=@VERSION@
DIRT_TIMESTAMP=1028570784
DIRT_BRANCH_ID=23

@GLOBUS_SCRIPT_INITIALIZER@

. ${libexecdir}/globus-script-initializer

globus_source ${libexecdir}/globus-sh-tools.sh

short_usage="globus-personal-gatekeeper [-help] [-start] [-list] [-killall] ..."

long_usage ()
{
    ${GLOBUS_SH_CAT-cat} >&2 <<EOF

Syntax: globus-personal-gatekeeper [options]

    [options]
    -help
    -usage
    Displays usage

    -version
    Displays version

    -debug
    Displays extra output

    -start [-jmtype <type>] [-auditdir <dir>] [-port <port>] [-log[=DIRECTORY]] [-seg] [-acctfile file]
    Starts a new gatekeeper, mapping default service to a
    jobmanager. By default, the jobmanager is configured with
    jmtype=fork. The option -port can be used to restrict the
    gatekeeper to use a particular port. The default is to let the
    system choose a port. The -log switch causes the job manager
    to write log messages to files in DIRECTORY.
    If -seg is used, then the Scheduler Event Generator will be used to 
    poll job state. The -auditdir switch tells the jobmanager where
    to store the audit-records. The -acctfile switch tells the gatekeeper
    where to log accounting records.

    -list
    Scans for active personal gatekeepers. If found, an
    authentication test is made to determine if the gatekeeper is
    still functioning.  If the authentictation test succeeds, the
    contact to that gatekeeper is printed out.

    -directory <contact>
    Returns the temporary directory used by the personal
    gatekeeper associated with <contact>. The directory contains
    grid-mapfile, log file, etc.

    -kill <contact>
    Finds and kills the personal gatekeeper associated with
    <contact>.

    -killall
    Finds all personal gatekeepers running on the local host and
    kills them.

EOF
}


globus_source ${libexecdir}/globus-args-parser-header $*

debug=:

verify_setup ()
{
    hours=""
    ${debug} "verifying setup..."

    if test "$1" != 'kill'; then
        hours="-hours 1"
    fi
    ${bindir}/grid-proxy-info -exists $hours
    
    if [ $? -ne 0 ]; then
        echo "ERROR: no valid proxy, or lifetime to small (one hour)" >&2
        exit 1
    fi

    ${debug} "done."
}


get_jm_arg_value()
{
    desired="$1"
    shift

    while [ "$#" -gt 0 ]; do
        if [ "$1" = "$desired" ]; then
            echo "$2"
            break
        fi
        shift;
    done
}

killem ()
{
    found=false
    foundit=false

    if test -z "${GLOBUS_SH_WHOAMI}"; then
	if test -z "${LOGNAME}"; then
	    user=$USER
	else
	    user=$LOGNAME
	fi
    else
	user=`${GLOBUS_SH_WHOAMI}`
    fi
    for dir in `ls -1d ${file_location}/${file_prefix}* 2> /dev/null`
    do
        if [ -n "${dir}" ]; then
            found=true
            if [ -r ${dir}/gatekeeper.log ]; then
                contact="`${GLOBUS_SH_GREP-grep} 'GRAM contact' ${dir}/gatekeeper.log |
                    ${GLOBUS_SH_TAIL-tail} -1 |
                    ${GLOBUS_SH_SED-sed} 's/^.*GRAM contact: //'`"
                ${debug} "found contact= [${contact}]"
            fi

            dokill=false
            if [ -z "$1" ]; then
                dokill=true
            else
                if [ "$1" = "$contact" ]; then
                    dokill=true
                    foundit=true
                fi
            fi

            if [ $dokill = true ]; then

                echo "killing gatekeeper: \"${contact}\""
                if [ -r ${dir}/gatekeeper.pid ]; then
                    pid=`${GLOBUS_SH_CAT-cat} ${dir}/gatekeeper.pid`
                    ${GLOBUS_SH_KILL-kill} -9 $pid &
                fi
                cd
		statedir="${TMPDIR:-/tmp}/${user}/`echo \"${dir}\" | sed -e 's|.*/||'`"
                if [ -r ${dir}/jobmanager.conf ]; then
                    host=`${bindir}/globus-hostname | ${GLOBUS_SH_CUT-cut} -d. -f1`
                    args=`cat "${dir}/jobmanager.conf"`
                    service_tag="`eval get_jm_arg_value -service-tag $args`"
                    if [ "$service_tag" = "" ]; then
                        service_tag=untagged
                    fi
                    lrm="`eval get_jm_arg_value -type $args`"
                    tagged="$HOME/.globus/job/$host/$lrm.$service_tag"
                    pidfile="$tagged.pid"
                    sockfile="$tagged.sock"
                    lockfile="$tagged.lock"
                    credfile="$tagged.cred"
                    jmpid=""
                    if [ -r "$pidfile" ]; then
                        read jmpid < "$pidfile"
                    fi
                    if [ "$jmpid" != "" ]; then
                        kill $jmpid
                    fi
                    [ -e "$pidfile" ] && ${GLOBUS_SH_RM-rm} "$pidfile"
                    [ -e "$sockfile" ] && ${GLOBUS_SH_RM-rm} "$sockfile"
                    [ -e "$lockfile" ] && ${GLOBUS_SH_RM-rm} "$lockfile"
                    [ -e "$credfile" ] && ${GLOBUS_SH_RM-rm} "$credfile"
                fi

                ${GLOBUS_SH_RM-rm} -rf ${dir} &
		${GLOBUS_SH_RM-rm} -rf "${statedir}" &
            fi
        fi
    done

    if [ $found = false ]; then
        echo "No personal gatekeepers found on this host."
    fi

    if [ -n "$1" -a ${foundit} = false ]; then
        echo "Could not find the personal gatekeeper you specified."
    fi
}


findit ()
{
    foundit=false
    for dir in `ls -1d ${file_location}/${file_prefix}* 2>/dev/null`
    do
        if [ -n "${dir}" ]; then
            found=true
            if [ -r ${dir}/gatekeeper.log ]; then
                contact="`${GLOBUS_SH_GREP-grep} 'GRAM contact' ${dir}/gatekeeper.log |
                    ${GLOBUS_SH_TAIL-tail} -1 |
                    ${GLOBUS_SH_SED-sed} 's/^.*GRAM contact: //'`"

                if [ "$1" = "$contact" ]; then
                    foundit=true
                    echo "${dir}"
                fi
            fi
        fi
    done

    if [ ${foundit} = false ]; then
        echo "Could not find the personal gatekeeper you specified."
    fi
}


listem ()
{
    found=false
    foundold=false
    for dir in `ls -1d ${file_location}/${file_prefix}* 2> /dev/null`
    do
        if [ -n "${dir}" ]; then
            found=true
            if [ -r ${dir}/gatekeeper.log ]; then
                contact="`${GLOBUS_SH_GREP-grep} 'GRAM contact' ${dir}/gatekeeper.log |
                    ${GLOBUS_SH_TAIL-tail} -1 |
                    ${GLOBUS_SH_SED-sed} 's/^.*GRAM contact: //'`"
                ${debug} "found contact= [${contact}]"
                ${bindir}/globusrun -a -r "${contact}" 1>/dev/null 2>/dev/null
                if [ $? -eq 0 ]; then
                    echo "${contact}"
                else
                    ${debug} "could not authenticate to the contact -- old"
                    foundold=true
                fi
            fi
        fi
    done

    if [ $found = false ]; then
        echo ""
        echo "no personal gatekeepers found on this host"
    fi

    if [ $foundold = true ]; then
        echo ""
        echo "Found old non-functioning personal gatekeeper(s). Please use"
        echo "this command with the -killall option to clean them up."
    fi
}


cleanup ()
{
    if [ ${docleanup} = true ]; then
        ${GLOBUS_SH_RM-rm} -rf ${scratch}
        ${GLOBUS_SH_RM-rm} -rf ${statefiledir}
        docleanup=false
    fi
}



jmtype=fork
port=
docleanup=false
startnew=false
host=`${bindir}/globus-hostname| ${GLOBUS_SH_CUT-cut} -d. -f1`
file_location="$HOME/.globus/."
file_prefix="gram.$host"
log=never
seg=0
startargs=''
single=''
logdir=""
valgrind=0

while [ -n "$1" ]; do
    case "$1" in
    -kill)
    verify_setup kill
    killem "$2"
    exit 0
    ;;
    -killall)
    verify_setup kill
    killem ""
    exit 0
    ;;
    -list)
    listem
    exit 0
    ;;
    -directory)
    findit "$2"
    exit 0
    ;;
    -start)
    startnew=true
    shift
    while [ -n "$1" ]; do
        case $1 in
	    -jmtype)
		jmtype="$2"
		shift
		;;
	-log*)
                logdir=`expr "$1" : "-log=\(.*\)"`
                if [ "$logdir" = "" ]; then
                    logdir="$HOME"
                fi
		;;
        -single)
                single="$1"
                ;;
        -valgrind)
                valgrind=1
                ;;
	-port)
		port="$2"
		shift
		;;
        -seg)
                seg=1
                ;;
	-auditdir)
                auditdir="$2"
                shift
                ;;
        -acctfile)
                acctfile="$2"
                shift;
                ;;
        *)
		startargs="$startargs $1"
		;;
	esac
	shift
    done
    break
    ;;
    -debug)
    debug=echo
    ;;
    *)  
    globus_args_unrecognized_option "$1"
    ;;
    esac
    shift
done

if [ $startnew != true ]; then
    globus_args_short_usage
    exit 1
fi

if test -z "${GLOBUS_SH_WHOAMI}"; then
    if test -z "${LOGNAME}"; then
        user=$USER
    else
        user=$LOGNAME
    fi
else
    user=`${GLOBUS_SH_WHOAMI}`
fi

if test -z "${user}"; then
    echo "ERROR: globus-personal-gatekeeper: can not determine user name" >&2
    exit 1
fi

verify_setup

scratch="${file_location}/${file_prefix}.$$"
statefiledir="${TMPDIR:-/tmp}/${user}/${file_prefix}.$$"

trap cleanup 0 1 2 3 6 9 12 15


docleanup=true
${GLOBUS_SH_MKDIR-mkdir} -p ${scratch}
${GLOBUS_SH_MKDIR-mkdir} -p "${statefiledir}"

if test $? != 0; then
    echo "Error making state file dir (${statefiledir})." 1>&2
    exit 1
fi

for file in gridmap services.conf gatekeeper.conf jobmanager.conf gatekeeper.log ; do
    ${GLOBUS_SH_RM-rm} -f ${scratch}/${file}
done

subject=`${bindir}/grid-proxy-info -identity`

${GLOBUS_SH_CAT-cat} > ${scratch}/gridmap <<EOF
"${subject}" ${user}
EOF

if [ $valgrind -eq 1 ]; then
    valgrind=`which valgrind`
    if [ $? -ne 0 ]; then
        echo "Error: can't find valgrind" 1>&2
        exit 1
    fi
${GLOBUS_SH_CAT-cat} > ${scratch}/jobmanager <<EOF
stderr_log,local_cred - $valgrind valgrind --leak-check=full --leak-resolution=high --show-reachable=yes --log-file=${HOME}/valgrind.%p.log ${sbindir}/globus-job-manager -conf ${scratch}/jobmanager.conf
EOF
else
${GLOBUS_SH_CAT-cat} > ${scratch}/jobmanager <<EOF
stderr_log,local_cred - ${sbindir}/globus-job-manager globus-job-manager -conf ${scratch}/jobmanager.conf
EOF
fi

${GLOBUS_SH_CAT-cat} > ${scratch}/gatekeeper.conf <<EOF
-gridmap ${scratch}/gridmap
-home ${GLOBUS_LOCATION:-@exec_prefix@}
-e ${sbindir}
-logfile ${scratch}/gatekeeper.log
-grid_services ${scratch}
-d 
EOF

if [ -n "$port" ]; then
    echo "-port $port" >> ${scratch}/gatekeeper.conf
fi

if [ ! -z "${acctfile}" ]; then
    echo "-acctfile $acctfile" >> ${scratch}/gatekeeper.conf
fi


host_info=`${libexecdir}/config.guess`
host_cputype=`echo $host_info | ${GLOBUS_SH_AWK-awk} -F'-' '{print $1}'`
host_manufacturer=`echo $host_info | ${GLOBUS_SH_AWK-awk} -F'-' '{print $2}'`
host_osname=`${GLOBUS_SH_UNAME-uname} -s`
host_osversion=`${GLOBUS_SH_UNAME-uname} -r`
if [ "$logdir" != "" ]; then
    log_line=`echo "-stdio-log \"$logdir\""`
    log_levels="-log-levels 'FATAL|ERROR'"
fi

if [ -x "${bindir}/globus-version" ]; then
  globus_toolkit_version="`${bindir}/globus-version`"
else
  globus_toolkit_version="Unknown"
fi

${GLOBUS_SH_CAT-cat} > ${scratch}/jobmanager.conf <<EOF
-home ${GLOBUS_LOCATION:-@exec_prefix@}
-type ${jmtype}
-globus-gatekeeper-subject "${subject}"
-globus-host-cputype ${host_cputype}
-globus-host-manufacturer ${host_manufacturer}
-globus-host-osname ${host_osname}
-globus-host-osversion ${host_osversion}
$log_line
$log_levels
-state-file-dir ${statefiledir}
${startargs}
$single
${X509_CERT_DIR:+-x509-cert-dir "$X509_CERT_DIR"}
-globus-toolkit-version "$globus_toolkit_version"
-service-tag "${file_prefix}.$$"
EOF


if [ ! -z "${auditdir}" ]; then
    ${GLOBUS_SH_CAT-cat} >> ${scratch}/jobmanager.conf <<EOF
-audit-directory ${auditdir}
EOF
fi

if test $seg -eq 1; then
    echo "-seg-module $jmtype" >> ${scratch}/jobmanager.conf
fi

docleanup=false
 
${sbindir}/globus-gatekeeper -c ${scratch}/gatekeeper.conf -test \
    1>/dev/null 2>/dev/null
x=$?
if [ $x -ne 0 ]; then
    echo "ERROR: gatekeeper was not properly configured" >&2
    docleanup=true
    exit 1
fi

${sbindir}/globus-gatekeeper -c ${scratch}/gatekeeper.conf < /dev/null > /dev/null 2>/dev/null  &
x=$?
pid=$!
if [ $x -ne 0 ]; then
    echo "ERROR: gatekeeper did not start up properly" >&2
    docleanup=true
    exit 1
fi
echo "$pid" > ${scratch}/gatekeeper.pid

contact=
shallexit=
count=0
while [ ${count} -lt 10 -a -z "${contact}" -a -z "${shallexit}" ]; do
    ${GLOBUS_SH_SLEEP-sleep} 1
    contact="`${GLOBUS_SH_GREP-grep} 'GRAM contact' ${scratch}/gatekeeper.log`"
    shallexit="`${GLOBUS_SH_GREP-grep} FAILED_PLEASE_EXIT ${scratch}/gatekeeper.log`"
    count=`${GLOBUS_SH_EXPR-expr} ${count} + 1`
done

if [ ${count} -ge 10 -o -n "${shallexit}" ]; then
    echo "ERROR: gatekeeper did not start up properly" >&2
    docleanup=true
    exit 1
else
    host=`echo "$contact" | ${GLOBUS_SH_CUT-cut} -d: -f5`
    port=`echo "$contact" | ${GLOBUS_SH_CUT-cut} -d: -f6`

    ${GLOBUS_SH_CAT-cat} >> ${scratch}/jobmanager.conf <<EOF
-globus-gatekeeper-host $host
-globus-gatekeeper-port $port
EOF
    echo "$contact" | ${GLOBUS_SH_SED-sed} -e 's/^.*GRAM contact:/GRAM contact:/'
fi


exit 0
