#!/bin/bash
# $Id: ovpn_gen_client.bash 1037 2026-03-16 15:07:58Z bertrand $
# Ce script permet de générer un fichier de configuration pour un 
# client OpenVPN.
# external parameters
ovpn_path=$1
target_path=$2
profile_name=$3
client_name=$4
# internal parameters
RED=$(tput setaf 1)
GREEN=$(tput setaf 2)
YELLOW=$(tput setaf 3)
RESET=$(tput sgr0)
# ovpn
ovpn_config_path="client"
ovpn_config_name="$profile_name.ovpn"
ovpn_config_file="$ovpn_path/$ovpn_config_path/$ovpn_config_name"
# ca
ca_path="$ovpn_path/ca"
ca_pki_path="$ca_path/pki"
ca_ta_cert_file="$ca_path/ta.key"
ca_ca_cert_file="$ca_pki_path/ca.crt"
ca_issued_path="$ca_pki_path/issued"
ca_private_path="$ca_pki_path/private"
ca_client_crt_file="$ca_issued_path/$client_name.crt"
ca_client_key_file="$ca_private_path/$client_name.key"
ca_client_pem_file="$ca_issued_path/$client_name.pem"
# target
target_file="$target_path/$profile_name-$client_name.ovpn"
# tools
openssl_tool=$(which openssl)
openssl_cmdline="$openssl_tool x509"
# actual work
if [[ -n $ovpn_path && -n $target_path && -n $profile_name &&-n $client_name && -f $ovpn_config_file && -n $openssl_tool ]]; then
	if [[ ! -f $target_file ]]; then
		if [[ -f $ca_client_pem_file ]]; then
			rm -f $ca_client_pem_file
		fi
		$openssl_cmdline -in $ca_client_crt_file -out $ca_client_pem_file -outform PEM
		cp $ovpn_config_file $target_file
		echo "key-direction 1" >> $target_file
		echo "<ca>" >> $target_file
		cat $ca_ca_cert_file >> $target_file
		echo "</ca>" >> $target_file
		echo "<cert>" >> $target_file
		cat $ca_client_pem_file >> $target_file
		echo "</cert>" >> $target_file
		echo "<key>" >> $target_file
		cat $ca_client_key_file >> $target_file
		echo "</key>" >> $target_file
		echo "<tls-auth>" >> $target_file
		cat $ca_ta_cert_file >> $target_file
		echo "</tls-auth>" >> $target_file
		echo "${GREEN}configuration for $client_name generated ($target_file)${RESET}"
	else
		echo "${YELLOW}configuration for $client_name ($target_file) already exists${RESET}"
	fi
else
	if [[ -n $ovpn_path ]]; then
		if [[ -z $target_path ]]; then
			echo "${RED}target_path cannot be empty${RESET}"
		fi
		if [[ -z $profile_name ]]; then
			echo "${RED}profile_name cannot be empty${RESET}"
		else
			if [[ ! -f $ovpn_config_file ]]; then
				echo "${RED}$ovpn_config_file does not exist${RESET}"
			fi
		fi
		if [[ -z $client_name ]]; then
			echo "${RED}client_name cannot be empty${RESET}"
		fi
	else
		echo "usage: $0 ovpn_path target_path profile_name client_name"
	fi
	if [[ -z $openssl_tool ]]; then
		echo "${RED}openssl not found${RESET}"
	fi
fi
