#!/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@

function usage() {
    v_here_echo << HEREDOC
$SELF_SHORTNAME: Get the environment variable value for another user

Usage: ./$SELF_SHORTNAME [-u USER] -e VAR

USER:  Get the value for this user, rather than the current user
VAR:   The environment variable name.

Exit status:
    0   if success
    1   for general improper usage errors or internal errors
HEREDOC
}

TARGETUSER=""
VARNAME=""
while getopts :hu:e: OPTVAL; do
    case "$OPTVAL" in
        h )
            usage
            exit 0
            ;;
        u )
            TARGETUSER="$OPTARG"
            ;;
        e )
            VARNAME="$OPTARG"
            ;;
        \? )
            echo "Invalid option: -$OPTARG" >&2
            exit 1
            ;;
    esac
done

shift $(( $OPTIND - 1 ))

if [ "$VARNAME" = "" ]; then
    echo "No environment variable name provided" >&2
    usage >&2
    exit 1
fi

if [ "$#" != "0" ]; then
    echo "Unexpected arguments: $*" >&2
    usage >&2
    exit 1
fi

CMD="echo \"\${$VARNAME:-}\""

if [ ! -z "$TARGETUSER" ]; then
    # invoke the inner script as user in a login shell.
    if [ "$EUID" != "0" ]; then
        echo "Must be root when specifying -u. EUID = $EUID" >&2
        exit 1
    fi

    "$BIN_SU" "$TARGETUSER" --login --shell "$BIN_BASH" --command "$CMD"
    exit "$?"
else
    eval "$CMD"
    exit "$?"
fi
