#!/usr/bin/env bash

set -euo pipefail

echo "================================"
echo "Entered orchestration env loader"
echo "Binary to execute is $@"

cd /opt/zoox/ai/zoox

# Set all environmental variables.
source "scripts/vehicle/common.sh"

# There is a known bug in ssh that the remote processes will become orphan if
# a pty is not allocated. We use the method described here
# https://bugzilla.mindrot.org/show_bug.cgi?id=396#c14 to circumvent the
# problem. It is basically an EOF to SIGTERM converter that sends SIGTERM to
# remote processes when the ssh connection is closed.
TUBE=/tmp/orchestration_remote_fifo.$$
rm -f "$TUBE"
mkfifo "$TUBE"

<"$TUBE" $@ &  appPID=$!

cat >"$TUBE"
sudo kill -TERM $appPID
rm -f "$TUBE"
