#!/bin/sh
#
# Usage: addvpnprofile.sh [Number] [email]
#
export EASYRSA=/etc/openvpn/easy-rsa

newclient () {
	# Build client certificate
	cd $EASYRSA
	# enable TLS-ECDHE-ECDSA-WITH-AES-256-GCM-SHA384 for TLS connections
	EASYRSA_CERT_EXPIRE=3650 easyrsa --vars=/etc/easy-rsa/vars --curve=secp521r1 --use-algo=ec --batch build-client-full $2 nopass
	if [ "$?" != "0" ]; then
      echo "Error, could not create the client certificate for profile!"
      exit -3
	fi
	# Generates the custom client.ovpn
	cp /etc/openvpn/client-common.txt /etc/openvpn/clientprofiles/$1.ovpn
	echo "<ca>" >> /etc/openvpn/clientprofiles/$1.ovpn
	cat $EASYRSA/pki/ca.crt >> /etc/openvpn/clientprofiles/$1.ovpn
	echo "</ca>" >> /etc/openvpn/clientprofiles/$1.ovpn
	echo "<cert>" >> /etc/openvpn/clientprofiles/$1.ovpn
	sed -ne '/BEGIN CERTIFICATE/,$ p' $EASYRSA/pki/issued/$2.crt >> /etc/openvpn/clientprofiles/$1.ovpn
	echo "</cert>" >> /etc/openvpn/clientprofiles/$1.ovpn
	echo "<key>" >> /etc/openvpn/clientprofiles/$1.ovpn
	cat $EASYRSA/pki/private/$2.key >> /etc/openvpn/clientprofiles/$1.ovpn
	echo "</key>" >> /etc/openvpn/clientprofiles/$1.ovpn
	echo "<tls-auth>" >> /etc/openvpn/clientprofiles/$1.ovpn
	sed -ne '/BEGIN OpenVPN Static key/,$ p' /etc/openvpn/ta.key >> /etc/openvpn/clientprofiles/$1.ovpn
	echo "</tls-auth>" >> /etc/openvpn/clientprofiles/$1.ovpn
	# Done
	echo
	echo "Client $1 added, configuration is available at:" /etc/openvpn/clientprofiles/"$1.ovpn"
	exit 0
}

if [ -d /etc/openvpn/easy-rsa ]; then
  if [ "$1" != "" ] && [ "$2" != "" ]; then
    newclient $1 $2
    if [ "$?" != 0 ]; then
      echo "Error while trying to create the profile $1.ovpn for user $2."
      exit -3
    fi
    echo "Added profile $2."
    exit 0
  else
    echo "No profile name given!"
    exit -2
  fi
else
  echo "OpenVPN not configured!"
  exit -1
fi
