#!/bin/bash

# @PREAMBLE_START@

# This section is copied from preamble.sh (automatically, during build) and
# should not be edited in place.

# turn on echo for debuging.
if [ ! -z "${VERT_DEBUG_PREAMBLE:-}" ]; then set -x; else set +x; fi
: '# Preamble begin'
: '# # Standardizing shell'
unset IFS # default word splitting on whitespace
set +o history # disable history. Should be default, but some reports otherwise
set -u # disallow unset variables

# note: these two vars are reset by vars.bash, but necessary to get there.
VERT_D=${VERT_VERT_D:-'/opt/vertica'}
BINLIB_D=${VERT_BINLIB_D:-"$VERT_D/share/binlib"}
source "$BINLIB_D/include/vars.bash"
source "$BINLIB_D/include/common_func.bash"
source "$BINLIB_D/include/self_vars.bash"

: '# Preamble end'
set +x # turn echo off
# @PREAMBLE_END@

# TODO: allow an option to list all pids.
function usage() {
	v_here_echo << HEREDOC
$SELF_SHORTNAME: Use \`ps\` to find the first pid of one of the specified commands.

Usage: ./$SELF_SHORTNAME NAME [NAME ...]

Names must be the basename of the program, like you would use with \`ps -C\`.

Prints the first instance of the binary found (like the 'which' command).  The
return code indicates whether or not the binary was found.
HEREDOC
}

for BINNAME in "$@"; do
	if [ -z "$BINNAME" ]; then
		echo "Empty name provided. Ignoring" >&2
		continue
	fi

    PSOUT="$("$BIN_PS" -C "$BINNAME" -o 'pid=')"

    read -r FIRSTPID <<< "$PSOUT"

    if [ ! -z "$FIRSTPID" ]; then
        echo "$FIRSTPID"
        exit 0
    fi
done

exit 1

# TODO getopt
