#!/bin/bash

#   m     h  dom mon dow   command
#   *  8-19  *   *   1-5   /opt/ssh_tunnels_cron.sh start
#   5    20  *   *   1-5   /opt/ssh_tunnels_cron.sh stop

ssh_socket="/tmp/ssh_tunnel_myuser.sock"
ssh_user="myuser"
tunnels="-R *:10022:localhost:22   $tunnels"
tunnels="-R *:13000:localhost:3000 $tunnels"
tunnels="-R *:13001:localhost:3001 $tunnels"
tunnels="-R *:15910:localhost:5910 $tunnels"
tunnels="-L   10022:localhost:22   $tunnels" # "check alive" tunnel for on an eventual IP change
config="-o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -o ConnectTimeout=5"
options="-f -nNT -M -S $ssh_socket -l $ssh_user -q $config $tunnels"

case "$1" in
  start)
    # stop it if already running
    ssh $config -o BatchMode=yes -o ConnectTimeout=3 -p 10022 $ssh_user@localhost exit > /dev/null 2> /dev/null && exit 0
    /opt/ssh_tunnels_cron.sh stop # paranoia
    # start it
    exec ssh $options `/opt/bin/getip_casa` > /dev/null 2> /dev/null
    ;;

  stop)
    ssh -S $ssh_socket -O exit xxx  > /dev/null 2> /dev/null ; sleep 2
    pkill -f -QUIT "ssh.*$ssh_user" > /dev/null 2> /dev/null # paranoia
    ;;

  *)
    echo "Usage: `basename $0` <start|stop>"
esac
