#! /bin/sh

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

# IANA allocated port
GRIS_PORT=2135

print_last_arg ()
{
  while test "$#" -gt 1
  do
    shift
  done

  echo "$1"
}

get_filename_base ()
{
  IFS_save="$IFS"
  IFS=/
  print_last_arg $1
  IFS="$IFS_save"
}

print_short_usage ()
{
commandname=`get_filename_base "$0"`
if test "$#" -gt 0
then
  echo "$commandname" "$@"
fi

cat <<EOF
usage: ${commandname} [-h host] [-p port] [option]... <filter> [attr]...

Use '-help' for full usage

EOF
}

long_usage ()
{

commandname=`get_filename_base "$0"`

cat <<EOF
usage: ${commandname} [option]... <filter> [attribute]...

   Performs standard MDS search operation with default host:port as
   described below, by processing args and invoking grid-info-search.

   options: 

        {-h|-mdshost} hostname
            Search service at hostname instead of localhost.

        {-p|-mdsport} port
            Search service at port instead of GRIS port (2135).

        {-help|-usage}
            Print this help information and exit.

        All standard grid-info-search options are also supported;
        see grid-info-search -help for details.

EOF

}

. ${GLOBUS_LOCATION}/libexec/globus-args-parser-header

# set defaults
SEARCH_HOST=localhost
SEARCH_PORT=${GRIS_PORT}

SEARCH_ARGS=

# scan options for special parameters, and save the rest
while test "$#" -gt 0
do
  case "$1"
  in
    -h | -mdshost)
      SEARCH_HOST="$2"
      if test "$#" -gt 1
      then
        shift 2
      else
        shift 1
      fi
      ;;
    -p | -mdsport)
      SEARCH_PORT="$2"
      if test "$#" -gt 1
      then
        shift 2
      else
        shift 1
      fi
      ;;
    *)
      SEARCH_ARGS="${SEARCH_ARGS} \"$1\""
      shift
      ;;
  esac
done

# prepend special options to all the uninterpreted ones
SEARCH_INVOCATION="${bindir}/grid-info-search -h \"${SEARCH_HOST}\""
SEARCH_INVOCATION="${SEARCH_INVOCATION} -p \"${SEARCH_PORT}\""
SEARCH_INVOCATION="${SEARCH_INVOCATION} ${SEARCH_ARGS}"

# exec the underlying search query.
# eval handles all the quoting that has been preserved/inserted above
eval "exec ${SEARCH_INVOCATION}"

