#!/bin/sh

# tools
PTYREDIR=/usr/local/bin/pty-redir
SSH=/usr/bin/ssh
PPPD=/usr/sbin/pppd
ROUTE=/sbin/route
SLEEP=/bin/sleep
KILL=/bin/kill
HEAD=/usr/bin/head
ECHO=/bin/echo
SUDO=/usr/bin/sudo

# addressing
MYPPPIP=192.168.10.1
REMOTEPPPIP=192.168.10.2
REMOTENET=192.168.3.0
REMOTEMASK=255.255.255.0

# account
REMOTEHOST=utopia.lifehertz.com
REMOTEUN=vpn

if [ "$UID" -eq 0 ]; then
	case "$1" in
		start)
			# establish connection
			$ECHO "Establishing SSH connection to $REMOTEHOST..."
			$PTYREDIR $SSH -l $REMOTEUN $REMOTEHOST > /tmp/vpndev
			$SLEEP 10

			# Start PPP
			$ECHO "Starting PPP daemon..."
			$PPPD $(cat /tmp/vpndev) linkname $REMOTEUN local noauth proxyarp persist $MYPPPIP:$REMOTEPPPIP
			$SLEEP 10

			# add route
			$ECHO "Configuring routing..."
			$ROUTE add -net $REMOTENET $REMOTEPPPIP

			# Uncomment this for default gateway remote machine:
			# $ROUTE add -net 0.0.0.0 $REMOTEPPPIP

			$ECHO "Done."
			;;
		stop)
			# Bring down PPP
			$ECHO "Killing PPP daemon..."
			$KILL $($HEAD -n 1 /var/run/ppp-$REMOTEUN.pid)
			;;
		*)
			$ECHO "Usage: vpn (start|stop)"
			;;
	esac
else
	$ECHO "This program should be run as root or with root privileges."
	$ECHO "sudo $0 $@"
	$SUDO $0 $@
fi