#!/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: Test the ability to access a file (or directory) as a user.

Usage: ./$SELF_SHORTNAME [-u USER] FILE

USER:  The user to test access as. If not specified, self.
FILE:  The file to test access to. Read access is checked.

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

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

shift $(( $OPTIND - 1 ))

if [ "$#" -lt "1" ]; then
    echo "FILE not specified" >&2
    usage >&2
    exit 1
fi

CHECKFILE="$1"

shift 1

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

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

    CMD="[ -r $(printf '%q' "$CHECKFILE") ]"

    "$BIN_SU" "$TARGETUSER" --login --shell "$BIN_BASH" --command "$CMD" || exit 2
else
    # Check as self
    [ -r "$CHECKFILE" ] || exit 2
fi
