#!/bin/bash
set -e

USAGE="Usage: $0 [-p port] <portforward> <hostconnection> <command>"

if [ $# -lt 2 ]; then
  echo "$USAGE"
  exit 1
fi

OPTIND=1
PORT=""
KEYFILE=""

while getopts "h?p:i:" opt; do
    case "$opt" in
    h|\?)
        echo "$USAGE"
        exit 1
        ;;
    p)  PORT=$OPTARG
        ;;
    i)  KEYFILE=$OPTARG
        ;;
    esac
done

shift $((OPTIND-1))

[ "${1:-}" = "--" ] && shift

SSH_OPTS=""

if [ -n "$PORT" ]; then
  SSH_OPTS="${SSH_OPTS} -p ${PORT}"
fi

if [ -n "$KEYFILE" ]; then
  SSH_OPTS="${SSH_OPTS} -i ${KEYFILE}"
fi

CONTROLFILE="/tmp/tunnelwrap.$RANDOM"
PORTFORWARD="$1"
shift
HOSTCONNECTION="$1"
shift

ssh -M -S $CONTROLFILE -fnNT -L $PORTFORWARD $SSH_OPTS $HOSTCONNECTION
"$@"
ssh -S $CONTROLFILE -O exit $HOSTCONNECTION
