#!/bin/bash
# Script for automating the creation of an OpenVPN client.

_TMP=`id | cut -d '=' -f 2 | cut -b 1`
if [ $_TMP != 0 ]
then
	echo "I'm sorry but you need to run this as root!"
	exit
fi

if [ -e /etc/openvpn/client-creator-settings ]
then
	source /etc/openvpn/client-creator-settings
else
	echo I require a configuration file called /etc/openvpn/client-creator-settings. You should reinstall the epochvpn package or create this file by hand.
	exit 1
fi

if [ "$1" = "" ] || [ "$2" = "" ]; then
	echo "Usage: $0 [client_name] (Win|Lin)"
	exit 1
fi

client=$1

# make a directory to store the client's conf in case we need it again
if [ ! -d /etc/openvpn/clients/$client ]; then
	mkdir -p /etc/openvpn/clients/$client
fi

clientdir="/etc/openvpn/clients/$client"

# test clienttype - W for Windows, L for Linux, B for Both
type=`echo $2 | cut -b 1`

case "$type" in
'W')
	EXT="ovpn"
	targetdir="C:\Program Files\OpenVPN\config"
	;;
'L')
	EXT="conf"
	targetdir="/etc/openvpn"
	;;
*)
	echo "Second parameter must begin with W (Windows) or L (Linux)"
	exit 1
esac


userdir=`pwd`

cd /etc/openvpn/easy-rsa
. ./vars > /dev/null
./pkitool --pkcs12 $client

# keep an additional copy of the key
cp keys/$client.p12 $clientdir

# create the clientconfig file
if [ "$MS" == "true" ]; then
        echo "Enter MS client ID:"
        read client_id
        echo "ifconfig-push 172.24.$client_id.1 255.255.0.0
        iroute 172.26.$client_id.0 255.255.255.0" > $CCD/$client
fi

# don't output another 'remote' directive unless we have a secondary server
if [ $SECONDARY_SERVER ]; then
        SEC_REMOTE="remote $SECONDARY_SERVER"
fi

# create the client conf file
echo "dev $TUNDEVICE

remote $PRIMARY_SERVER
$SEC_REMOTE
port $PORT
nobind
comp-lzo

client
pkcs12 $client.p12
ns-cert-type server
pull

verb 4
mute 10
" > $clientdir/$1-$VPNNAME.$EXT

cd $clientdir
zip ~/$client.zip *

echo "I have created a zip file in your home dir called $client.zip"
echo "Copy it to the vpn client machine, unzip it and place the key and $EXT file under $targetdir"
echo "If you want specific settings for this client (eg a push route), enter them in $CCD/$client"
echo "NOTE: the IP that the client connects on via the 'remote' directive in the conf file must be the same as the IP it receives a reply on. If you are contacting a server with multiple IPs (eg with a dmz subnet), you may need to set a specific IP in the 'remote' directive (eg if the client is in the dmz)."

cd $userdir
