#!/bin/bash

# This script wraps the behavior of establishing a tunnel on a remote
# host that comes back here to this system.

# Edit these variables as necessary

# Port we are using to establish this tunnel
sshPort=22
# Port that will be used to tunnel back to this system
localPort=22

# User and host of remote system
remoteUser=$USER
remoteHost=remotehost

# Port to use the tunnel, like this:
#   remoteHost$ ssh -p 2022 localUser@localhost
remotePort=2022

# Note: If the remoteHost is a "middleman" system, you can connect
# straight back through it in one shot by adding to
# remoteHost:/etc/ssh/sshd_config
#   GatewayPorts yes

# Time in seconds to wait before attempting to reestablish the tunnel
sleepTime=300

# The command for establishing the tunnel
# May want to add -X or -Y for X11 forwarding, if desired
command="ssh -p $sshPort -N -R $remotePort:localhost:$localPort $remoteUser@$remoteHost"


function log {
   echo "$(date +"%F %T")> $1"
}


# This will keep trying to restore the tunnel any time it's down
while true
do
   log "Starting tunnel with this command:"
   echo "   $command"
   echo "   Press ctrl-c twice to REALLY stop"
   $command
   log "Stopped. Restarting in $sleepTime secs"
   sleep $sleepTime
   log "Restarting now"
done
