#! /bin/sh

ldapbindir=/usr/bin
tmpdir=/var/run/arc/infosys

# no more than three times per minute
MIN_SLAVE_REG_TIME=20

# no less than 5 second cache TTL
MIN_DAEMON_CACHETIME=5

# get everything by default
DEFAULT_DAEMON_SIZELIMIT=0

# set default network timeout to 30 seconds
DEFAULT_NETWORK_TIMEOUT=""

short_usage_error ()
{
  if test "$#" -gt 0
  then
    echo grid-info-soft-register: "$@" 1>&2
    ldap_shell_log_error "$@"
  else
    ldap_shell_log_error "unknown problem"
  fi


  cat 1>&2 <<EOF
usage: grid-info-soft-register [-log <logfile>] -f[ile] <conffile>       \\
                               -- <daemon> [arg...]
   or: grid-info-soft-register [-log <logfile>] -r[egister] <reg-clause> \\
                               -d[aemon] <daemon-clause>
   or: grid-info-soft-register -h[elp]
EOF
}

usage_error ()
{
  short_usage_error

  cat 1>&2 <<EOF

       reg-clause:
                     -t[ype] mdsreg[2] -h[ost] <hostname> -p[ort] <port>  \\
                     -period <seconds> -dn <DN>

       daemon-clause:
                     -t[ype] ldap -h[ost] <hostname> -p[ort] <port>    \\
                     -ttl <seconds> -r[oot] <DN>                       \\
                     {-T|-timeout} <seconds>                           \\
                     {-b|-bindmethod} <AUTHC-ONLY/AUTHC-FIRST/ANONYM-ONLY> \\
                     [{-z|-sizelimit} <objects>]                       \\
                     [-m[ode] cachedump -period <seconds>]

       The first form (with configuration file) is normally used
       explicitly, while the second form is used internally. The first
       form starts the daemon with its arguments and registers the
       daemon service using the information in the conf file for as
       long as the daemon runs.  If given the TERM signal, the program
       will try to kill the daemon before exiting.

       The second form performs the requested registration directly until
       killed by any signal, without starting any daemon.
EOF
}

ldap_shell_log_event ()
{
  if test ! "X${GRID_INFO_SYSTEM_LOGFILE}" = "X"
  then
    echo `date` "${THIS_COMMAND_BASE} [$$]: log:" "$@" \
      >> "${GRID_INFO_SYSTEM_LOGFILE}"
  fi
}

ldap_shell_log_error ()
{
  if test ! "X${GRID_INFO_SYSTEM_ERRORFILE}" = "X"
  then
    echo `date` "${THIS_COMMAND_BASE} [$$]: error:" "$@" \
      >> "${GRID_INFO_SYSTEM_ERRORFILE}"
  fi
}



###########################################################################
# process command-line
INVOCATION_MODE=

if test ! "$#" -gt 0
then
  short_usage_error
  exit 1
fi

arg_check ()
{
  value=`eval echo '$'{$1}`

  if test -z "$value"
  then
    short_usage_error "missing $2"
    exit 1
  fi
}

expand_path ()
{
  path_in="$1"

  while test ! "${path_in}" = `eval echo ${path_in}`
  do
    path_in=`eval echo ${path_in}`
  done

  echo "${path_in}"
}


clear_slave_params ()
{
     SLAVE_REG_HOST=
     SLAVE_REG_PORT=
     SLAVE_REG_TYPE=
     SLAVE_REG_TIME=
     SLAVE_REG_DN=

     SLAVE_DAEMON_HOST=
     SLAVE_DAEMON_PORT=
     SLAVE_DAEMON_TYPE=
     SLAVE_DAEMON_TIME=
     SLAVE_DAEMON_TIMEOUT=
     SLAVE_DAEMON_BINDMETHOD=
     SLAVE_DAEMON_CACHETIME=
     SLAVE_DAEMON_DN=
     SLAVE_DAEMON_MODE=direct
     SLAVE_DAEMON_SIZELIMIT=${DEFAULT_DAEMON_SIZELIMIT}
}

while test "$#" -gt 0
do
  case "$1"
  in
    -h | -help)
       usage_error
       exit 0
       ;;
    -log)
       if test "$#" -eq 1
       then
         short_usage_error "invalid last argument \"$1\""
         exit 1
       fi
       GRID_INFO_SYSTEM_LOGFILE="$2"
       GRID_INFO_SYSTEM_ERRORFILE="$2"
       shift 2
       ;;
    -f | -file)
       if test "$#" -eq 1
       then
         short_usage_error "invalid last argument \"$1\""
         exit 1
       fi
       INVOCATION_MODE=master
       MASTER_CONF_FILE="$2"
       shift 2
       ;;
    -p | -pid)
       if test "$#" -eq 1
       then
         short_usage_error "invalid last argument \"$1\""
         exit 1
       fi
       MASTER_PID="$2"
       shift 2
       ;;
    --)
       if test ! "$#" -ge 2 || \
          test ! "X${INVOCATION_MODE}" = "Xmaster"
       then
         short_usage_error "missing required arguments"
         exit 1
       fi

       MASTER_DAEMON_PATH="$2"

       # leave daemon args in positional parameters
       shift 2

       if test ! -r "${MASTER_CONF_FILE}"
       then
         short_usage_error "cannot read file \"${MASTER_CONF_FILE}\""
         exit 2
       fi

       if test ! -x "${MASTER_DAEMON_PATH}"
       then
         short_usage_error "cannot execute \"${MASTER_DAEMON_PATH}\""
         exit 2
       fi

       break
       ;;
    -r | -register)
       INVOCATION_MODE=slave

       SLAVE_CLAUSE=register

       clear_slave_params

       shift 1

       while test "$#" -gt 0
       do
         if test "$#" -eq 1
         then
           short_usage_error "invalid last argument \"$1\""
           exit 1
         fi

         if test "$1" = "-d" || \
            test "$1" = "-daemon"
         then
           SLAVE_CLAUSE=daemon
           shift 1
         fi

         case "${SLAVE_CLAUSE}:$1"
         in
           register:-t | register:-type)
             SLAVE_REG_TYPE="$2"
             ;;
           register:-h | register:-host)
             SLAVE_REG_HOST="$2"
             ;;
           register:-p | register:-port)
             SLAVE_REG_PORT="$2"
             ;;
           register:-period)
             SLAVE_REG_TIME="$2"
             if test "${SLAVE_REG_TIME}" -lt ${MIN_SLAVE_REG_TIME}
             then
               ldap_shell_log_event "clamping period to minimum ${MIN_SLAVE_REG_TIME}"
               echo "clamping period to minimum ${MIN_SLAVE_REG_TIME}" 1>&2
             fi
             ;;
           register:-dn)
             SLAVE_REG_DN="$2"
             ;;
           daemon:-t | daemon:-type)
             SLAVE_DAEMON_TYPE="$2"
             ;;
           daemon:-h | daemon:-host)
             SLAVE_DAEMON_HOST="$2"
             ;;
           daemon:-p | daemon:-port)
             SLAVE_DAEMON_PORT="$2"
             ;;
           daemon:-ttl)
             SLAVE_DAEMON_TIME="$2"
             ;;
           daemon:-T | daemon:-timeout)
             SLAVE_DAEMON_TIMEOUT="$2"
             ;;
           daemon:-b | daemon:-bindmethod)
             SLAVE_DAEMON_BINDMETHOD="$2"
             ;;
           daemon:-z | daemon:-sizelimit)
             SLAVE_DAEMON_SIZELIMIT="$2"
             ;;
           daemon:-r | daemon:-root)
             SLAVE_DAEMON_DN="$2"
             ;;
           daemon:-m | daemon:-mode)
             SLAVE_DAEMON_MODE="$2"
             ;;
           daemon:-period)
             SLAVE_DAEMON_CACHETIME="$2"
             if test "${SLAVE_DAEMON_CACHETIME}" -lt "${MIN_DAEMON_CACHETIME}"
             then
               ldap_shell_log_event "clamping cache period to minimum ${MIN_DAEMON_CACHETIME}"
               echo "clamping period to minimum ${MIN_DAEMON_CACHETIME}" 1>&2
             fi
             ;;
           *)
             short_usage_error "unexpected argument \"$1\""
             ;;
         esac

         shift 2
       done

       arg_check SLAVE_REG_HOST      "registration host"
       arg_check SLAVE_REG_PORT      "registration port"
       arg_check SLAVE_REG_TYPE      "registration type"
       arg_check SLAVE_REG_TIME      "registration period"

       if test "${SLAVE_REG_TYPE}" = "mdsreg"
       then
         arg_check SLAVE_REG_DN      "registration DN"
       elif test "${SLAVE_REG_TYPE}" = "mdsreg2"
       then
         arg_check SLAVE_REG_DN      "registration DN"
       else
         short_usage_error "unrecognized registration" \
           "type \"${SLAVE_REG_TYPE}\""
       fi

       
       arg_check SLAVE_DAEMON_HOST   "daemon host"
       arg_check SLAVE_DAEMON_PORT   "daemon port"
       arg_check SLAVE_DAEMON_TIME   "daemon registration TTL"
       arg_check SLAVE_DAEMON_TYPE   "daemon type"
       arg_check SLAVE_DAEMON_BINDMETHOD   "daemon bind method"

       if test "${SLAVE_DAEMON_TYPE}" = "ldap"
       then
         arg_check SLAVE_DAEMON_DN   "LDAP daemon root DN"
         arg_check SLAVE_DAEMON_TIMEOUT "LDAP daemon query timeout"
       fi

       if test "${SLAVE_DAEMON_MODE}" = "cachedump"
       then
         arg_check SLAVE_DAEMON_CACHETIME "daemon cache period"
       fi

       ;;
    *)
       short_usage_error "missing -- separator"
       exit 2
       ;;
  esac
done

# end argument processing
##############################################################
# do real work

SLAVE_PIDS_FILE=${tmpdir}/grid-info-soft-register.pids.$$
SLAVE_PIDS=
DAEMON_PID=

cleanup ()
{
  case "${INVOCATION_MODE}"
  in
    master)
      if test -r ${SLAVE_PIDS_FILE}
      then
        SLAVE_PIDS="${SLAVE_PIDS} "`cat ${SLAVE_PIDS_FILE}`
        rm -f ${SLAVE_PIDS_FILE}
      fi
      if test ! -z "${SLAVE_PIDS}"
      then
        kill -15 ${SLAVE_PIDS} 2> /dev/null
        SLAVE_PIDS=
      fi
      if test ! -z "${DAEMON_PID}"
      then
        kill -15 ${DAEMON_PID} 2> /dev/null
        sleep 2
        kill -9 ${DAEMON_PID} 2> /dev/null
        DAEMON_PID=
      fi
      ;;
    slave)
      :
      ;;
  esac
}

soft_sleep ()
{
  SLEEPER_PID=

  sleep $* &
  SLEEPER_PID="$!"

  wait $SLEEPER_PID
}

kill_wrap ()
{
    _max_time=$1
    shift

    "$@" 2> /dev/null > /dev/null &
    KILL_PID="$!"

    soft_sleep $1
    kill -TERM "$KILL_PID"
    kill -9 "$KILL_PID"
}

trap cleanup 0

mdsreg_ldapadd ()
{
        if test -x ${ldapbindir}/ldapadd
        then
                tmpfile=`mktemp`
                while read line ; do echo $line >> $tmpfile ; done

                if [ "X$SLAVE_DAEMON_BINDMETHOD" = "XAUTHC-ONLY" ]
                then
                        ${ldapbindir}/ldapadd -h "${SLAVE_REG_HOST}" \
                             -p "${SLAVE_REG_PORT}" $DEFAULT_NETWORK_TIMEOUT \
                            < $tmpfile || \
                        ${ldapbindir}/ldapadd -h "${SLAVE_REG_HOST}" \
                             -p "${SLAVE_REG_PORT}" $DEFAULT_NETWORK_TIMEOUT \
                             -D "${SLAVE_REG_DN}" -w "dummy" \
                            < $tmpfile
                else
                        ${ldapbindir}/ldapadd -x -h "${SLAVE_REG_HOST}" \
                             -p "${SLAVE_REG_PORT}" $DEFAULT_NETWORK_TIMEOUT \
                            < $tmpfile || \
                        ${ldapbindir}/ldapadd -x -h "${SLAVE_REG_HOST}" \
                             -p "${SLAVE_REG_PORT}" $DEFAULT_NETWORK_TIMEOUT \
                             -D "${SLAVE_REG_DN}" -w "dummy" \
                            < $tmpfile

                fi

                unlink $tmpfile
        else
            ldap_shell_log_error "cannot execute \"${ldapbindir}/ldapadd\""
        fi
}

mdsreg_register ()
{
    # follow original MDS 2.0 registration "schema"

    if test ! -z "${SLAVE_DAEMON_CACHETIME}"
    then
      cacheline="cachettl: ${SLAVE_DAEMON_CACHETIME}"
    fi

    mdsreg_ldapadd <<EOF
dn: ${SLAVE_REG_DN}
hn: ${SLAVE_DAEMON_HOST}
port: ${SLAVE_DAEMON_PORT}
rootdn: ${SLAVE_DAEMON_DN}
ttl: ${SLAVE_DAEMON_TIME}
type: ${SLAVE_DAEMON_TYPE}
timeout: ${SLAVE_DAEMON_TIMEOUT}
bindmethod: ${SLAVE_DAEMON_BINDMETHOD}
mode: ${SLAVE_DAEMON_MODE}`if test ! -z "$cacheline" ; \
                           then echo "" ; echo "$cacheline" ; fi`

EOF

    result=$?
}

mdsreg_register2 ()
{
    if test ! -z "${SLAVE_DAEMON_CACHETIME}"
    then
      cacheline="Mds-Service-Ldap-cachettl: ${SLAVE_DAEMON_CACHETIME}"
    fi

    SLAVE_DAEMON_TIME2=$SLAVE_DAEMON_TIME

    validfrom=`date -u +"%Y%m%d%H%M%SZ"`
    validto=`date -u +"%Y%m%d%H%M%SZ" -d"+$SLAVE_DAEMON_TIME seconds"`
    keepto=`date -u +"%Y%m%d%H%M%SZ" -d"+$SLAVE_DAEMON_TIME2 seconds"`

    mdsreg_ldapadd <<EOF
dn: ${SLAVE_REG_DN}
objectclass: Mds
objectclass: MdsVoOp
objectclass: MdsService
objectclass: MdsServiceLdap
Mds-Vo-Op-name: register
Mds-Service-type: ${SLAVE_DAEMON_TYPE}
Mds-Service-protocol: 0.1
Mds-Service-hn: ${SLAVE_DAEMON_HOST}
Mds-Service-port: ${SLAVE_DAEMON_PORT}
Mds-Service-Ldap-suffix: ${SLAVE_DAEMON_DN}
Mds-Service-Ldap-sizelimit: ${SLAVE_DAEMON_SIZELIMIT}
Mds-Bind-Method-servers: ${SLAVE_DAEMON_BINDMETHOD}
Mds-validfrom: ${validfrom}
Mds-validto: ${validto}
Mds-keepto: ${keepto}
Mds-Service-Ldap-timeout: ${SLAVE_DAEMON_TIMEOUT}`if test ! -z "$cacheline" ; \
                           then echo "" ; echo "$cacheline" ; fi`

EOF
    
    result=$?
}

case "${INVOCATION_MODE}"
in
  master)
    if [ -n "${MASTER_PID}" ] ; then
      DAEMON_PID=${MASTER_PID}
      ldap_shell_log_event "Tracking PID ${MASTER_PID}"
    else
      # start daemon
      ${MASTER_DAEMON_PATH} "$@" > /dev/null 2> /dev/null &
      DAEMON_PID="$!"

      ldap_shell_log_event "started daemon" \
        "PID=${DAEMON_PID} \"${MASTER_DAEMON_PATH}\""
    fi

    # start slave registration processes
    clear_slave_params
    # initialize an empty SLAVE_PIDS_FILE
    cat /dev/null > ${SLAVE_PIDS_FILE}
    # force a newline at EOF
    { cat "${MASTER_CONF_FILE}" ; echo "" ; } | \
    while read name value
    do
      if test -z "${name}"
      then
        if test ! -z "${SLAVE_REG_HOST}"    && \
           test ! -z "${SLAVE_REG_TYPE}"    && \
           test ! -z "${SLAVE_REG_PORT}"    && \
           test ! -z "${SLAVE_REG_TIME}"    && \
           test ! -z "${SLAVE_REG_DN}"      && \
           test ! -z "${SLAVE_DAEMON_TYPE}" && \
           test ! -z "${SLAVE_DAEMON_HOST}" && \
           test ! -z "${SLAVE_DAEMON_PORT}" && \
           test ! -z "${SLAVE_DAEMON_TIME}" && \
           test ! -z "${SLAVE_DAEMON_TIMEOUT}" && \
           test ! -z "${SLAVE_DAEMON_BINDMETHOD}" && \
           test ! -z "${SLAVE_DAEMON_SIZELIMIT}" && \
           test ! -z "${SLAVE_DAEMON_MODE}" && \
           test ! -z "${SLAVE_DAEMON_DN}"
        then
          # launch a slave
          if test ! -z "${GRID_INFO_SYSTEM_ERRORFILE}"
          then
            logclause="-log ${GRID_INFO_SYSTEM_ERRORFILE}"
          else
            logclause=
          fi
          $0 $logclause -register -t "${SLAVE_REG_TYPE}" -h "${SLAVE_REG_HOST}" -p "${SLAVE_REG_PORT}" -period "${SLAVE_REG_TIME}" -dn "${SLAVE_REG_DN}" -daemon -t "${SLAVE_DAEMON_TYPE}" -h "${SLAVE_DAEMON_HOST}" -p "${SLAVE_DAEMON_PORT}" -ttl "${SLAVE_DAEMON_TIME}" -r "${SLAVE_DAEMON_DN}" -T "${SLAVE_DAEMON_TIMEOUT}" -b ${SLAVE_DAEMON_BINDMETHOD} -z "${SLAVE_DAEMON_SIZELIMIT}" -m "${SLAVE_DAEMON_MODE}" -period "${SLAVE_DAEMON_CACHETIME}" 2> /dev/null > /dev/null &
          slave_pid="$!"
          echo " ${slave_pid}" >> ${SLAVE_PIDS_FILE}
          clear_slave_params
        fi
      else
        case "${name}"
        in
          dn:)
            SLAVE_REG_DN="${value}"
            ;;
          regtype:)
            SLAVE_REG_TYPE="${value}"
            ;;
          reghn:)
            SLAVE_REG_HOST="${value}"
            ;;
          regport:)
            SLAVE_REG_PORT="${value}"
            ;;
          regperiod:)
            SLAVE_REG_TIME="${value}"
            ;;
          hn:)
            SLAVE_DAEMON_HOST="${value}"
            ;;
          port:)
            SLAVE_DAEMON_PORT="${value}"
            ;;
          rootdn:)
            SLAVE_DAEMON_DN="${value}"
            ;;
          ttl:)
            SLAVE_DAEMON_TIME="${value}"
            ;;
          cachettl:)
            SLAVE_DAEMON_CACHETIME="${value}"
            ;;
          timeout: | timelimit:)
            SLAVE_DAEMON_TIMEOUT="${value}"
            ;;
          bindmethod:)
            SLAVE_DAEMON_BINDMETHOD="${value}"
            ;;
          sizelimit:)
            SLAVE_DAEMON_SIZELIMIT="${value}"
            ;;
          mode:)
            SLAVE_DAEMON_MODE="${value}"
            ;;
          type:)
            SLAVE_DAEMON_TYPE="${value}"
            ;;
          \#*)
            # discard comment fields
            :
            ;;
        esac
      fi
    done 

    SLAVE_PIDS=`cat ${SLAVE_PIDS_FILE}`

    if test -z "${SLAVE_PIDS}"
    then
      ldap_shell_log_event "zero registration records"
    else
      ldap_shell_log_event "started slave PIDs" ${SLAVE_PIDS}
    fi

    # wait for daemon
    while ( ps -p ${DAEMON_PID} > /dev/null) ; do
      soft_sleep 30
    done

    ldap_shell_log_event "daemon PID=${DAEMON_PID} terminated, exiting"

    DAEMON_PID=

    # kill slave registration processes
    cleanup
    ;;
  slave)
    # reregister every SLAVE_REG_TIME seconds, until killed
    ldap_shell_log_event "slave running on ${SLAVE_REG_TIME} interval"

    # give companion GIIS a chance to start before
    # first registration
    soft_sleep 5

    while true
    do

      case "${SLAVE_REG_TYPE}" in
        mdsreg)
          mdsreg_register
        ;;

        mdsreg2)
          mdsreg_register2
        ;;

        *)
          ldap_shell_log_error "unrecognized registration type \"${SLAVE_REG_TYPE}\""
          exit 1
        ;;
      esac

      soft_sleep "${SLAVE_REG_TIME}"
    done
    ;;
esac
