#!/bin/bash

# This script will execute the command passed as arguments.

# Setup the environment if not already done.

if [ x"$WARPDRIVE_ACTION" = x"" ]; then
    eval "$(warpdrive env)"
fi

WARPDRIVE_ACTION=exec
export WARPDRIVE_ACTION

WARPDRIVE_PROGRAM=$1

shift

# If running as process ID 1 and flagged that we should run as process
# ID 1, then simply exec the program. If not process ID 1, then always
# exec the program.

if [ $$ = 1 ]; then
    if [ x"$WARPDRIVE_RUN_AS_PID1" != x"" ]; then
        exec $WARPDRIVE_PROGRAM "$@"
    fi
else
    exec $WARPDRIVE_PROGRAM "$@"
fi

# Should only get here if running as process ID 1, but we don't want the
# program running as PID 1. In this case, if have 'tini', use it to
# manage the process, else try and manage from this script with some
# signal handling tricks so signals still propagated. We need to do this
# as can't rely on the program handling reaping of zombie processes
# properly. Note though that if fall through to backgrounding process,
# the program being run better not be wanting to read standard input
# as putting it in background will prevent that.

if ( which tini > /dev/null 2>&1 ); then
    exec tini -- $WARPDRIVE_PROGRAM "$@"
fi

trap 'kill -TERM $PID' TERM INT

$WARPDRIVE_PROGRAM "$@" &

PID=$!
wait $PID
trap - TERM INT
wait $PID
STATUS=$?
exit $STATUS
