#!/bin/sh

set -eu

SSH_CONNECTION=user@domain.tld
DOMAIN=tunnel.domain.tld

if [ $# -ne 2 ]; then
  echo "$(basename "$0") <name> <port>"
  echo "To establish a tunnel from https://name.${DOMAIN}/ to http://localhost:port/"
  exit 1
fi
TUNNEL_HOSTNAME="$1.${DOMAIN}"
TUNNEL_SOCKET="/tmp/tunnel-${TUNNEL_HOSTNAME}"
TUNNEL_PORT=$2

# remove the old tunnel socket if any
ssh "${SSH_CONNECTION}" -o RequestTTY=no rm -f "${TUNNEL_SOCKET}"

# connect the tunnel
ssh "${SSH_CONNECTION}" -f -N -R "${TUNNEL_SOCKET}:localhost:${TUNNEL_PORT}"

# fix the permissions on the tunnel
ssh "${SSH_CONNECTION}" -o RequestTTY=no chmod a+rw "${TUNNEL_SOCKET}"

echo "Connect to: https://${TUNNEL_HOSTNAME}/"
