#!/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 create subprocesses of various niceness

Usage: ./$SELF_SHORTNAME [-u USER] [-0] -v VALUE[,VALUE...]

USER:  su to this user first, with a login shell.
-0:    Ensure niceness starts at 0
VALUE: A value between -20 and 19 to nice to.  Subsequent VALUEs will be handled
       by that subprocess.

Exit status:
    0   if success
    1   for general improper usage errors or internal errors
    3   if unable to set niceness
    4   if not starting at 0 and -0 is provided.
HEREDOC
}

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

shift $(( $OPTIND - 1 ))

if [ "$NICELEVELS" = "" ]; then
    echo "No nice levels provided" >&2
    usage >&2
    exit 1
fi

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

NICE_CHAIN_IMPL="$(v_dirname "$SELF_EXEC")/nice-chain-impl"

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=`printf '%q' "$NICE_CHAIN_IMPL"`
    CMD="$CMD -v $(printf '%q' "$NICELEVELS")"

    if [ -n "$START_AT_ZERO" ]; then
        CMD="$CMD -0"
    fi

    CMD="$CMD -b $(printf '%q' "$BIN_BASH") -p $(printf '%q' "$BIN_PS")"

    "$BIN_SU" "$TARGETUSER" --login --shell "$BIN_BASH" --command "$CMD"
    RCODE="$?"
    exit "$RCODE"
else
    # invoke the inner script as ourself.
    if [ -n "$START_AT_ZERO" ]; then
        "$NICE_CHAIN_IMPL" -p "$BIN_PS" -b "$BIN_BASH" -v "$NICELEVELS" -0
        RCODE="$?"
    else
        "$NICE_CHAIN_IMPL" -p "$BIN_PS" -b "$BIN_BASH" -v "$NICELEVELS"
        RCODE="$?"
    fi
    exit "$RCODE"
fi
