#!/bin/sh

if test -z "${GLOBUS_LOCATION}"; then 
    echo "" 
    echo "ERROR: Please set GLOBUS_LOCATION to the Globus installation directory before" 
    echo "running this script" 
    echo "" 
    exit 1 
fi 


DELIM=
if [ -n "$LD_LIBRARY_PATH" ]; then
    DELIM=:
fi

LD_LIBRARY_PATH="$GLOBUS_LOCATION/lib$DELIM$LD_LIBRARY_PATH"

. ${GLOBUS_LOCATION}/libexec/globus-script-initializer
globus_source ${libexecdir}/globus-sh-tools.sh

. ${GLOBUS_LOCATION}/libexec/globus-personal-gatekeeper-version.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>] [-port <port>] [-log=always|never|on_error]
    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 choose when log files will be created in the user's home directory.

    -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 ()
{
    ${debug} "verifying setup..."

    bindir="${GLOBUS_LOCATION}/bin"
    sbindir="${GLOBUS_LOCATION}/sbin"
    libexecdir="${GLOBUS_LOCATION}/libexec"

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

    ${debug} "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 `${GLOBUS_SH_FIND-find} ${file_location} \
        -name .gass_cache -prune -exec /bin/true {} \; -o \
        -name ${file_prefix}\* -type d -print 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="${local_tmpdir}/${user}/`echo \"${dir}\" | sed -e 's|.*/||'`"
                ${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 `${GLOBUS_SH_FIND-find} ${file_location} \
        -name .gass_cache -prune -exec /bin/true {} \; -o \
        -name ${file_prefix}\* -type d -print 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/\^.\*$host/$host/`"

                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 `${GLOBUS_SH_FIND-find} ${file_location} \
        -name .gass_cache -prune -exec /bin/true {} \; -o \
        -name ${file_prefix}\* -type d -print 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/\^.\*$host/$host/`"
                ${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`
file_location="$HOME/.globus"
file_prefix="personal-gatekeeper.$host"
log=never
startargs=''

while [ -n "$1" ]; do
    case "$1" in
    -kill)
    verify_setup
    killem "$2"
    exit 0
    ;;
    -killall)
    verify_setup
    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)
		if test "$2" = "on_error" -o "$2" = "always" -o "$2" = "never"
                then
		    log=$2
		else
		    globus_args_unrecognized_option "$1"
		fi
		shift
		;;
	-port)
		port="$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="${local_tmpdir}/${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

    ${GLOBUS_SH_CAT-cat} > ${scratch}/jobmanager <<EOF
stderr_log,local_cred - ${libexecdir}/globus-job-manager globus-job-manager -conf ${scratch}/jobmanager.conf
EOF

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

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

host_info=`${sbindir}/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`

    ${GLOBUS_SH_CAT-cat} > ${scratch}/jobmanager.conf <<EOF
-home ${GLOBUS_LOCATION}
-type ${jmtype}
-rdn jobmanager 
-globus-gatekeeper-subject "${subject}"
-globus-host-cputype ${host_cputype}
-globus-host-manufacturer ${host_manufacturer}
-globus-host-osname ${host_osname}
-globus-host-osversion ${host_osversion}
-save-logfile ${log}
-machine-type unknown
-state-file-dir ${statefiledir}
${startargs}
EOF

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

eval "(${sbindir}/globus-gatekeeper -c ${scratch}/gatekeeper.conf) &"
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: -f4`
    port=`echo "$contact" | ${GLOBUS_SH_CUT-cut} -d: -f5`

    ${GLOBUS_SH_CAT-cat} >> ${scratch}/jobmanager.conf <<EOF
-globus-gatekeeper-host $host
-globus-gatekeeper-port $port
EOF

fi


exit 0
