lördag 5 januari 2013

VPN autoconnect

I recently signed up for a VPN service and wanted to make sure that it always connects to the service on startup, keeps the connection up and makes sure that my torrent program is only running when the VPN service is up.
To accomplish this I made a stupid script for KDE.

So in the name of sharing, here is the script. Enjoy. Feedback appreciated.

 #!/bin/bash

# Settings
# your torrent software
TORRENT="ktorrent"
# start qdbusviewer, open org.kde.networkmanagement. Nagivage to org/kde/networkmanagement/Activatable/x
# x is your network interfaces enumerated. In each of them navigate to x/org.kde.networkmanagement.InterfaceConnection/Method: connectionName
# By using the connectionName method you will be able to figure out which of the enumerated interfaces that is your VPN connection.
ACTIVATABLE="1"

PID="$HOME/kde_openvpn.pid"
LOG="$HOME/kde_openvpn.log"

if [ $# -eq 0 ]; then
 if [ -e $LOG ]; then
  mv $LOG ${LOG}.1
 fi

 if [ -e $PID ]; then
  ps -u $(whoami) -o pid,args|grep -i $(cat $PID)|grep -i "kde-openvpn-autoreconnect.sh" > /dev/null
        if [ $? -eq 0 ]; then
   kill $(cat $PID)
        fi
 fi

 $0 "fork" 2>&1 1>$LOG &
 exit
fi

echo $$ > $PID

FSM=0
while true; do
 # activateState 0: not connected, 1: progress?, 2: connected
 if [ $(qdbus org.kde.networkmanagement /org/kde/networkmanagement/Activatable/$ACTIVATABLE activationState) = 0 ]; then
        FSM=1
  echo "$FSM VPN down, killing all programs and reconnects"
  killall $TORRENT
  qdbus org.kde.networkmanagement /org/kde/networkmanagement/Activatable/$ACTIVATABLE activate
    elif [ $FSM = 1 -a $(qdbus org.kde.networkmanagement /org/kde/networkmanagement/Activatable/$ACTIVATABLE activationState) = 2 ]; then
        FSM=2
        echo "$FSM VPN connected"
 fi

    if [ $FSM = 2 ]; then
        FSM=0
        echo "$FSM Starting torrent"
        $TORRENT &
    fi
 sleep 30
done