#!/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=globus_gram_job_manager
VERSION=15.10
DIRT_TIMESTAMP=1765327864
DIRT_BRANCH_ID=0

prefix="${GLOBUS_LOCATION-/usr}"
exec_prefix="${prefix}"
sbindir="${exec_prefix}/sbin"
bindir="${exec_prefix}/bin"
libdir="${prefix}/lib/powerpc64-linux-gnu"
includedir="/usr/include/globus"
datarootdir="${prefix}/share"
datadir="${datarootdir}"
libexecdir="/usr/share/globus"
sysconfdir="/etc"
sharedstatedir="${prefix}/com"
localstatedir="/var"

PATH=${sbindir}:${bindir}:${PATH}

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

long_usage ()
{
    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_args_short_usage()
{
    cat 1>&2 <<EOF

Syntax : ${short_usage}

Use -help to display full usage.

EOF
}

globus_args_option_error()
{
    cat 1>&2 <<EOF

ERROR: option $1 : $2
EOF
    globus_args_short_usage
    exit 1
}

globus_args_unrecognized_option()
{
    globus_args_option_error $1 "unrecognized option"
    exit 1
}

debug=:

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

    if test "$1" != 'kill'; then
        hours="-hours 1"
    fi
    #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

    user=${LOGNAME}
    user=${user:-$USER}
    user=${user:-`whoami`}
    for dir in `ls -1d ${file_location}/${file_prefix}* 2> /dev/null`
    do
        if [ -n "${dir}" ]; then
            found=true
            contact=
            if [ -r ${dir}/gatekeeper.log ]; then
                contact="`grep 'GRAM contact' ${dir}/gatekeeper.log |
                    tail -1 |
                    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=`cat ${dir}/gatekeeper.pid`
                    kill -9 $pid &
                fi
                cd
                statedir="${TMPDIR:-/tmp}/${user}/`echo \"${dir}\" | sed -e 's|.*/||'`"
                if [ -r ${dir}/jobmanager.conf ]; then
                    host=`globus_hostname`
                    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" ] && rm "$pidfile"
                    [ -e "$sockfile" ] && rm "$sockfile"
                    [ -e "$lockfile" ] && rm "$lockfile"
                    [ -e "$credfile" ] && rm "$credfile"
                fi

                rm -rf ${dir} &
                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
            contact=
            if [ -r ${dir}/gatekeeper.log ]; then
                contact="`grep 'GRAM contact' ${dir}/gatekeeper.log |
                    tail -1 |
                    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
            contact=
            if [ -r ${dir}/gatekeeper.log ]; then
                contact="`grep 'GRAM contact' ${dir}/gatekeeper.log |
                    tail -1 |
                    sed 's/^.*GRAM contact: //'`"
                ${debug} "found contact= [${contact}]"
                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
        rm -rf ${scratch}
        rm -rf ${statefiledir}
        docleanup=false
    fi
}



jmtype=fork
port=0
docleanup=false
startnew=false

globus_hostname()
{
    if command -v globus-hostname > /dev/null 2>&1; then
        globus-hostname | cut -d. -f1
    elif command -v hostname > /dev/null 2>&1; then
        hostname | cut -d. -f1
    elif command -v uname > /dev/null 2>&1; then
        uname -n | cut -d. -f1
    fi
}

host=`globus_hostname`
file_location="$HOME/.globus"
file_prefix="gram.$host"
log=never
seg=0
startargs=''
single=''
logdir=""
valgrind=0

while [ -n "$1" ]; do
    case "$1" in
    -help | -h | --help | -usage | --usage)
        long_usage
        exit 0
        ;;
    -version|--version)
        if [ "X${PROGRAM_NAME}" != "X" -a \
              "X${PROGRAM_VERSION}" != "X" ]; then
            echo "${PROGRAM_NAME}: ${PROGRAM_VERSION}"
        elif [ "X${PACKAGE}" != "X" -a \
               "X${VERSION}" != "X" ]; then
            echo "${PACKAGE}: ${VERSION}"
        else
            echo "No version information available."
        fi
        exit 0
        ;;
    -versions|--versions)
        __AT__=@
        if [ -n "${PACKAGE}" -a -n "${VERSION}" -a \
             -n "${DIRT_TIMESTAMP}" -a -n "${DIRT_BRANCH_ID}" -a \
             "X${DIRT_TIMESTAMP}" != "X${__AT__}DIRT_TIMESTAMP${__AT__}" -a \
             "X${DIRT_BRANCH_ID}" != "X${__AT__}DIRT_BRANCH_ID${__AT__}" ];
        then
            echo "${PACKAGE}: ${VERSION} (${DIRT_TIMESTAMP}-${DIRT_BRANCH_ID})"
        else
            echo "No DiRT information available."
        fi
        exit 0;
        ;;

    -kill)
    if test -z "$2" ; then
        echo "ERROR: -kill option requires a contact string" >&2
        exit 1
    fi
    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="$HOME"
                ;;
        -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;
                ;;
        *)
                if [ $(expr index "$1" " ") = 0 ]; then
		    startargs="$startargs $1"
                else
		    startargs="$startargs '$1'"
                fi
                ;;
        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

user=${LOGNAME:-$USER}
user=${user:-`id -un`}

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
mkdir -p "${scratch}"
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
    rm -f ${scratch}/${file}
done

subject=`grid-proxy-info -identity 2> /dev/null`
if [ $? != 0 ] || [ x"$subject" = x ]; then
    subject=`grid-cert-info -subject 2> /dev/null`
fi
if [ x"$subject" = x ]; then
    echo "Unable to determine security identity"
    exit 1
fi

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

if [ x"$JOBMANAGER_PATH" = x ]; then
    job_manager_path="$(command -v globus-job-manager)"
else
    job_manager_path="$JOBMANAGER_PATH/globus-job-manager"
fi

if [ $valgrind -eq 1 ]; then
    valgrind=`which valgrind`
    if [ $? -ne 0 ]; then
        echo "Error: can't find valgrind" 1>&2
        exit 1
    fi
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 ${job_manager_path} -conf ${scratch}/jobmanager.conf
EOF
else
cat > ${scratch}/jobmanager <<EOF
stderr_log,local_cred - ${job_manager_path} globus-job-manager -conf ${scratch}/jobmanager.conf
EOF
fi

cat > ${scratch}/gatekeeper.conf <<EOF
-gridmap ${scratch}/gridmap
-home ${GLOBUS_LOCATION:-${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


if [ -x ${libexecdir}/config.guess ]; then
    host_info=`${libexecdir}/config.guess`

    host_cputype=`echo $host_info | awk -F'-' '{print $1}'`
    host_manufacturer=`echo $host_info | awk -F'-' '{print $2}'`
else
    host_cputype=`uname -m`
    host_manufacturer=unknown
fi
host_osname=`uname -s`
host_osversion=`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

cat > ${scratch}/jobmanager.conf <<EOF
-home ${GLOBUS_LOCATION:-${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 "$$"
EOF


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

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

echo "-globus-job-dir ${TMPDIR:-/tmp}" >> ${scratch}/jobmanager.conf

docleanup=false

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

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
    sleep 1
    contact="`grep 'GRAM contact' ${scratch}/gatekeeper.log`"
    shallexit="`grep FAILED_PLEASE_EXIT ${scratch}/gatekeeper.log`"
    count=$((${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" | cut -d: -f5`
    port=`echo "$contact" | cut -d: -f6`

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


exit 0
