#!/bin/bash
# $Id: ovpn_new_client.bash 1037 2026-03-16 15:07:58Z bertrand $
# Ce script permet de créer un certificat pour un nouveau client 
# OpenVPN.
# external parameters
client_name=$1
# internal parameters
RED=$(tput setaf 1)
GREEN=$(tput setaf 2)
YELLOW=$(tput setaf 3)
RESET=$(tput sgr0)
# ovpn
ovpn_path="/etc/openvpn"
ovpn_clients="$ovpn_path/client.list"
# ca
ca_path="$ovpn_path/ca"
ca_pki_path="$ca_path/pki"
ca_issued_path="$ca_pki_path/issued"
ca_private_path="$ca_pki_path/private"
ca_reqs_path="$ca_pki_path/reqs"
ca_client_crt_file="$ca_issued_path/$client_name.crt"
ca_client_key_file="$ca_private_path/$client_name.key"
ca_client_req_file="$ca_reqs_path/$client_name.req"
# tools
easyrsa_tool="$ca_path/easyrsa"
easyrsa_cmdline="./easyrsa"
# actual work
if [[ -n $client_name && -f $ovpn_clients && -f $easyrsa_tool ]]; then
	if [[ ! -f $ca_client_crt_file && ! -f $ca_client_key_file && ! -f $ca_client_req_file ]]; then
		(cd $ca_path && $easyrsa_cmdline build-client-full $client_name nopass)
		if [[ -f $ca_client_crt_file && -f $ca_client_key_file && -f $ca_client_req_file ]]; then
			echo "${GREEN}new certificate for $client_name created${RESET}"
			echo $client_name >> $ovpn_clients
		else
			echo "${RED}failed to create new certificate for $client_name${RESET}"
			if [[ ! -f $ca_client_crt_file ]]; then
				echo "${RED}public key file \"$ca_client_crt_file\" does not exist${RESET}"
			fi
			if [[ ! -f $ca_client_key_file ]]; then
				echo "${RED}private key file \"$ca_client_key_file\" does not exist${RESET}"
			fi
			if [[ ! -f $ca_client_req_file ]]; then
				echo "${RED}request file \"$ca_client_req_file\" does not exist${RESET}"
			fi
		fi
	else
		echo "${RED}cannot create new certificate $client_name${RESET}"
		if [[ -f $ca_client_crt_file ]]; then
			echo "${YELLOW}public key file \"$ca_client_crt_file\" already exists${RESET}"
		fi
		if [[ -f $ca_client_key_file ]]; then
			echo "${YELLOW}private key file \"$ca_client_key_file\" already exists${RESET}"
		fi
		if [[ -f $ca_client_req_file ]]; then
			echo "${YELLOW}request file \"$ca_client_req_file\" already exists${RESET}"
		fi
	fi
else
	if [[ ! -f $ovpn_clients ]]; then
		echo "${RED}$ovpn_clients does not exist${RESET}"
	fi
	if [[ ! -f $easyrsa_tool ]]; then
		echo "{$RED}$easyrsa_tool does not exist${RESET}"
	fi
	if [[ -z $client_name ]]; then
		echo "usage: $0 client_name"
	fi
fi
