#!/bin/bash
function newClient() {
  CLIENT=$1

  RESULT=$(ssh -n VPNinstaller 'psql -At -d ossdip -U postgres -c "SELECT vpn_ip, vpn_password FROM users WHERE username = '\'$CLIENT\'' AND deleted_at IS NULL"')
  VPN_IP=$(echo "$RESULT" | awk -F\| '{print $1}')
  VPN_PASSWORD=$(echo "$RESULT" | awk -F\| '{print $2}')

  if [[ -z "$VPN_IP" ]]; then
		echo "The VPN IP address seems empty"
		logger "Failed to create username at vpn server, VPN IP is empty ${VPN_IP}"
		exit 4
  fi

	if [[ ! $CLIENT =~ ^[a-zA-Z0-9_-]+$ ]]; then
		echo "Username should only container alphanum, underscores and minus"
		logger "Failed to create username at vpn server, formatting issues for ${CLIENT}"
		exit 2
	fi

	CLIENTEXISTS=$(tail -n +2 /etc/openvpn/easy-rsa/pki/index.txt | grep -c -E "/CN=$CLIENT\$")
	if [[ $CLIENTEXISTS == '1' ]]; then
		echo "The specified client CN was already found in easy-rsa, please choose another name."
		logger "Failed to create username at vpn server, already exists in easy-rsa for ${CLIENT}"
		exit 3
	else
		cd /etc/openvpn/easy-rsa/ || return
    ./easyrsa build-client-full "$CLIENT" nopass
		logger "Client $CLIENT added."
		cat <<EOF > "/etc/openvpn/ccd/$CLIENT"
ifconfig-push $VPN_IP 255.0.0.0
iroute 172.27.48.129 255.255.255.128
push route $VPN_IP 255.0.0.0
EOF
		logger "Client $CLIENT has now static ip $VPN_IP"
	fi

	# write the .ovpn file to this dir
	homeDir="/var/opt/users/"
	mkdir -p $homeDir

	# Determine if we use tls-auth or tls-crypt
	if grep -qs "^tls-crypt" /etc/openvpn/server.conf; then
		TLS_SIG="1"
	elif grep -qs "^tls-auth" /etc/openvpn/server.conf; then
		TLS_SIG="2"
	fi

	# Generates the custom client.ovpn
	cp /etc/openvpn/client-template.txt "$homeDir/$CLIENT.ovpn"
	{
		echo "<ca>"
		cat "/etc/openvpn/easy-rsa/pki/ca.crt"
		echo "</ca>"

		echo "<cert>"
		awk '/BEGIN/,/END/' "/etc/openvpn/easy-rsa/pki/issued/$CLIENT.crt"
		echo "</cert>"

		echo "<key>"
		cat "/etc/openvpn/easy-rsa/pki/private/$CLIENT.key"
		echo "</key>"

		case $TLS_SIG in
		1)
			echo "<tls-crypt>"
			cat /etc/openvpn/tls-crypt.key
			echo "</tls-crypt>"
			;;
		2)
			echo "key-direction 1"
			echo "<tls-auth>"
			cat /etc/openvpn/tls-auth.key
			echo "</tls-auth>"
			;;
		esac
	} >>"$homeDir/$CLIENT.ovpn"

	echo "The configuration file has been written to $homeDir/$CLIENT.ovpn."
	exit 0
}

if [ $# -ne 1 ]; then
  echo "USAGE ./add-user username"
  exit 1
fi

newClient $1