#!/bin/bash

CONFDIR=/usr/share/applications/openvpn-config-server
OPENVPNDIR=/etc/openvpn

usage()
{
	echo "Usage: $0 <host name>"
	echo "Example: $0 client1"
	exit 1
}

bold()
{
	echo -e "\e[1m$1\e[0m"
}

HOST_NAME=$1

ID=`id -u`

if [ "${ID}" != "0" ]
then
	echo "You must be root in order to run this command"
	exit 1
fi

if [ -z "$1" ] || [ -n "$2" ]
then
	usage
fi

if [ -e ${CONFDIR}/keys/${HOST_NAME}.crt ]
then
	echo "The host name you are creating currently exists."
	echo "Please, remove files ${CONFDIR}/keys/${HOST_NAME}.crt and"
	echo "${CONFDIR}/keys/${HOST_NAME}.key before adding this server"
	echo "Do you want to automatically remove these files now? (y/N)"
	read -N 1 RES
	if [ "${RES}" == "y" ] || [ "${RES}" == "Y" ]
	then
		rm -f ${CONFDIR}/keys/${HOST_NAME}.crt
		rm -f ${CONFDIR}/keys/${HOST_NAME}.key
	else
		exit 1
	fi
fi

if ! [ -e ${CONFDIR}/keys/server.key ]
then
	echo "No server certificates found. Please, run openvpn-config-server"
	echo "first on server"
	exit 1
fi

bold "Generating client certs and keys..."

cd ${CONFDIR}
. vars
. build-key ${HOST_NAME}

bold "done."
