#!/usr/bin/env bash
###
# Wrapper script so I don't have to remeber all of the flags
# if you want this to go smoothly use ssh-copy-id to copy your public key to the VPS
###
HOST="<Proxy IP>"
USER="root"



while getopts 'l:r:' flag; do
  case $flag in
    v ) verbose=true;;
    l ) local_port=$OPTARG;;
    r ) remote_port=$OPTARG;;
  esac
done
shift $(($OPTIND-1)); OPTIND=1

usage="$(basename $0) -l <22> -r <19999>"
if [[ -z $local_port || -z $remote_port ]]; then
  echo "$usage"
  exit 1
fi
cmd="ssh -f -N -T -R ${remote_port}:localhost:${local_port} ${USER}@${HOST}"

trap "{ pkill -f \"$cmd\" ; exit 0 ; }" SIGINT

x=0
while true; do
  ((x++))

  # if the ssh command isn't running, run it
  [ -z "$(pgrep -f "$cmd")" ] && $cmd
  sleep 30m

  # kill off the ssh connection every so often
  mod=$(($x%5))
  if [ $mod == 0 ]; then
    pkill -f "$cmd"
    sleep 10
    pkill -9 -f "$cmd"
    sleep 10
  fi
done