# invokation: sh reverse-tunnel.sh
# 
# Downloaded from http://docpool.org/iphone/reverse-tunnel.sh.txt


# number of seconds to wait between each check
CHECK_INTERVAL=10

# last command must be the process sent into the background!
run_cmd() {
    ssh -C -nN -R *:8000:localhost:80 <your-login-on-remote-server>@<your-remote-server> &
#    sleep 300 & 
}

# set STATUS_VALUE to the current status-value to be checked
status(){
 # STATUS_VALUE=`date +"%s"` # dummy, not really useful, changes every sec...
 # use this for monitoring a
 STATUS_VALUE=`ifconfig en0 inet | sed -ne 's/.*inet \([^ ]*\) .*/\1/p' | head -1`
}

###END OF USERLAND



stop(){
#  if [ -n "$PID" ]; then
#    kill -9 $PID
#    PID=
#    pgrep sleep
#  fi
#
  return 0
}


start() {
 if [ -z "$PID" ]; then
   run_cmd
   PID=$!
   return 0
 fi

  return 1
}


OLD_STATUS_VALUE=
changed() {
status
if [ "${STATUS_VALUE}" = "$OLD_STATUS_VALUE" ]; then
  return 1
else
  OLD_STATUS_VALUE=${STATUS_VALUE}
  return 0
fi
}

run() {
  while changed && stop && start; do
    sh -T -c "trap '[ -n \"${PID}\" ] && kill -KILL ${PID}; exit 1' 2; sleep ${CHECK_INTERVAL}";
  done
}

run
