#!/bin/bash
#
# script for starting openvpn as TCP-Client

DEVICE="tun0"                       # tunnel device (tun0, tun1, ...)
REMOTE="athome.dyndns.org"          # (dynamic) host name of openvpn server
GATEWAY="192.168.1.254"             # IP of the local gateway which is
                                    # used to gain internet access
PORT="1194"                         # port number openvpn will use
LOCALIP="192.168.8.128"             # internal IP address of this client
REMOTEIP="192.168.8.1"              # internal IP address of the server
REMOTENET="192.168.42.0/24"         # netmask of the remote network
KEYFILE="/etc/openvpn/shared.key"   # name of the shared key file
MAXRATE="16000"                     # maximum tx transfer rate in bytes/s

# only run openvpn, if it is installed ;-)
if [ ! -x /usr/sbin/openvpn ]; then
  exit 1
fi

# check if we're allowed to dig the tunnel
while [ -e /etc/NOTUNNEL ]; do
  sleep 60
done

# dig the tunnel
/usr/sbin/openvpn --daemon --dev $DEVICE --remote $REMOTE --proto tcp-client \
  --port $PORT --ifconfig $LOCALIP $REMOTEIP --secret $KEYFILE --persist-tun \
  --ping 30 --ping-restart 180 --writepid /var/run/openvpn-${DEVICE}.pid

# try to set up the routing when interface is up, max. 10 retries
for ((i=0; i<10; i=$[$i+1])); do
  # probe for device by exit status of ifconfig
  ifconfig $DEVICE >/dev/null 2>/dev/null
  if [ "$?" -eq 0 ]; then
    route add $REMOTE gw $GATEWAY
    # probe if "route add" was successfull, then go on
    if [ "$?" -eq 0 ]; then
      route del default gw $GATEWAY
      route add -net $REMOTENET gw $REMOTEIP
      route add default gw $REMOTEIP
      ping -c 1 $REMOTEIP >/dev/null 2>/dev/null &
      break
    fi
  fi
  sleep 5
done

# Keep running, exit when the openvpn process is no longer present
while true; do
  # check if the PID file still exists
  if [ ! -e /var/run/openvpn-${DEVICE}.pid ]; then
    break
  else
    TUNNPID="`cat /var/run/openvpn-${DEVICE}.pid`"
  fi

  # probing with ps, returns "1" if process ID does not exist
  ps "$TUNNPID" >/dev/null 2>/dev/null
  if [ "$?" -gt 0 ]; then
    break
  else
    # now check if the process we found is really running openvpn
    if [ "`ps -o comm \"$TUNNPID\" | tail -n 1`" = "openvpn" ]; then
      sleep 60
    else
      break
    fi
  fi
done

# Do some cleanup
rm -f /var/run/openvpn-${DEVICE}.pid
route del $REMOTE gw $GATEWAY
route add default gw $GATEWAY
