#!/bin/sh

set -e

usage () {
	echo "Usage: pkgos-poc-run-on <poc-gateway> <node-ip> <script-file> [script-args...]"
	echo "       pkgos-poc-run-on <poc-gateway> --local <script-file> [script-args...]"
	echo ""
	echo "Run <script-file> as root on <node-ip> of an OCI PoC lab,"
	echo "hopping through <poc-gateway> (eg: bdbdev-oci-3). With --local,"
	echo "run the script on the gateway itself instead (eg: for pings"
	echo "which must originate from it). Extra arguments are passed to"
	echo "the script as its positional parameters."
	echo ""
	echo "The script and its arguments are piped over ssh as base64"
	echo "blobs, so neither goes through any shell parsing: stdout,"
	echo "stderr and exit code are the ones of the script itself. The"
	echo "ssh command strings are fixed code; user data never crosses"
	echo "a shell parse. Requires bash on the gateway and the nodes."
	exit 1
}

if [ $# -lt 3 ]; then
	usage
fi

GATEWAY=$1
NODE=$2
SCRIPT=$3
shift 3

if [ ! -r "${SCRIPT}" ]; then
	echo "ERROR: cannot read script file ${SCRIPT}"
	exit 1
fi

B64=$(base64 -w0 "${SCRIPT}")

# The script arguments travel as a NUL-separated base64 blob, decoded
# remotely: quoting them through the ssh hops any other way is a
# losing game. An empty blob means "no argument at all".
if [ $# -gt 0 ]; then
	ARGS_B64=$(printf '%s\0' "$@" | base64 -w0)
else
	ARGS_B64=""
fi

if [ "${NODE}" = "--local" ]; then
	cat <<EOF2 | ssh -o BatchMode=yes ${GATEWAY} bash
A64='${ARGS_B64}'
S64='${B64}'
ARGS=()
if [ -n "\$A64" ]; then
	while IFS= read -r -d '' a; do
		ARGS+=("\$a")
	done < <(echo "\$A64" | base64 -d)
fi
exec bash <(echo "\$S64" | base64 -d) "\${ARGS[@]}"
EOF2
else
	cat <<EOF2 | ssh -o BatchMode=yes ${GATEWAY} bash
A64='${ARGS_B64}'
S64='${B64}'
printf '%s\n%s\n' "\$A64" "\$S64" | ssh -o BatchMode=yes -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no root@${NODE} 'read -r A64
read -r S64
ARGS=()
if [ -n "\$A64" ]; then
	while IFS= read -r -d "" a; do
		ARGS+=("\$a")
	done < <(echo "\$A64" | base64 -d)
fi
exec bash <(echo "\$S64" | base64 -d) "\${ARGS[@]}"'
EOF2
fi
