#!/bin/sh
#
# VPN Init script for VPN using pppd over ssh
# Copyright (c) 1999  Dustin Sallings
# $Id: vpn,v 1.4 1999/02/22 07:12:10 dustin Exp $

# VARS
CONFIGS=/usr/pkg/etc/vpn

usage()
{
	echo "Usage:  $0 peer cmd"
	echo "Valid commands are as follows:"
	echo "    start"
	echo "    stop"
	echo "    authtest"
}

vpn_start()
{
	PEER=$1

	PTY=`$REDIR $SSH -e none -t -o 'Batchmode yes' -i $RSAKEY -l $SSHUSER \
		$PEER $REMOTEPPP $RPPPOPTIONS`

	echo "Issuing $REMOTEPPP $RPPPOPTIONS on $PTY"

	if [ "x$PTY" = "x" ]
	then
		echo "Failed to get a pty"
		exit 1
	fi

	$LOCALPPP $PTY $LOCALADDR:$REMOTEADDR $LPPPOPTIONS
}

vpn_authtest()
{
	$SSH -i $RSAKEY -l $SSHUSER $PEER true
	if [ $? -eq 0 ]
	then
		echo "Auth is OK"
	else
		echo "ssh failed auth"
	fi
}

vpn_stop()
{
	ID=`netstat -ain | egrep $LOCALADDR | awk '{print $1}' | sed s/ppp//`

	if [ "x$ID" = "x" ]
	then
		echo "Cannot find interface this peer is running on.  Is it running?"
	else
		if [ -f /var/run/ppp$ID.pid ]
		then
			PID=`cat /var/run/ppp$ID.pid`
		fi

		if [ "x$PID" = "x" ]
		then
			echo "Can't find PID file for $1"
		else
			echo "Shutting down"
			kill $PID
		fi
	fi
}

PEER=$1
CMD=$2

if [ "x$CMD" = "x" ]
then
	echo "Too few arguments!"
	usage
	exit 1
fi

# OK, there are enough arguments, let's see if they're correct.

if [ ! -f $CONFIGS/peers/$PEER ]
then
	echo "No such peer:  $PEER"
	exit 1
fi

# get the global config
. $CONFIGS/global.conf

# source the config
. $CONFIGS/peers/$PEER

case $CMD in
	start)
		vpn_start $PEER
	;;
	authtest)
		vpn_authtest $PEER
	;;
	stop)
		vpn_stop $PEER
	;;
	*)
		echo "Unknown command $CMD"
		usage
	;;
esac
