#!/usr/bin/bash

# We use this script instead of invoking ssh directly in order to
# facilitate easier unit testing where this script is replaced
# with one that simulates the ssh invocation.

opts=$SHELLOPTS
case $opts in
    *xtrace*)
        dir=$(dirname $(command -v $0))
        PROG=$(basename $(command -v $0))
        ;;
    *)
        dir=$(dirname $0)
        PROG=$(basename $0)
        ;;
esac

if [[ -z "${dir}" || -z "${PROG}" ]]; then
    echo "INTERNAL ERROR: bad environment encountered" >&2
    exit 1
fi

case $# in
    3)
        :
        ;;
    *)
        echo "Usage: $PROG <satellite-config> <output-tar-ball> <ssh-error>" >&2
        exit 1
        ;;
esac


satellite_config=$1
output_tar_ball=$2
errors=$3
shift 2

remote_host=$(pbench-config satellite-host $satellite_config)
if [ -z "${remote_host}" ]; then
    echo "$PROG: missing \"satellite-host\" configuration for \"${satellite_config}\"" >&2
    exit 1
fi
remote_opt=$(pbench-config satellite-opt $satellite_config)
if [ -z "${remote_opt}" ]; then
    echo "$PROG: missing \"satellite-opt\" configuration for \"${satellite_config}\"" >&2
    exit 1
fi

ssh ${remote_host} "${remote_opt}/bin/pbench-sync-package-tarballs" > ${output_tar_ball}  2> ${errors}
