#!/bin/bash
# $Id: ovpn_check_server.bash 1037 2026-03-16 15:07:58Z bertrand $
# Ce script permet de vérifier que le certificat serveur soit référencé.
# présent et valide.
# external parameters
# internal parameters
RED=$(tput setaf 1)
GREEN=$(tput setaf 2)
YELLOW=$(tput setaf 3)
RESET=$(tput sgr0)
# ovpn
ovpn_path="/etc/openvpn"
# 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_index_path="$ca_pki_path/index.txt"
# tools
openssl_tool=$(which openssl)
openssl_cmdline="$openssl_tool x509"
if [[ -d $ovpn_path ]]; then
	today=$(date +%s)
	server_cert_name="server"
	server_cert_path="$ca_issued_path/$server_cert_name.crt"
	echo -ne "$server_cert_name"
	cert_list=$(grep -w "CN=$server_cert_name" $ca_index_path)
	cert_count=$(echo $cert_list | wc -l)
	if [[ $cert_count > 0 ]]; then
		echo -ne "\t${GREEN}CERT_DB_ENTRY_FOUND${RESET}"
	else
		echo -ne "\t${RED}CERT_DB_ENTRY_NOT_FOUND${RESET}"
	fi
	if [[ -f $server_cert_path ]]; then
		echo -ne "\t${GREEN}CERT_FILE_FOUND${RESET}"
		cert_data=$($openssl_cmdline -dates -noout -in $server_cert_path)
		not_before=$(echo "$cert_data" | grep notBefore | cut -c 11-)
		not_after=$(echo "$cert_data" | grep notAfter | cut -c 10-)
		expiry_date=$(date -d "$not_after" +%s)
		if [[ $expiry_date > $today ]]; then
			echo -ne "\t${GREEN}CERT_DATE_VALID${RESET}"
		else
			echo -ne "\t${RED}CERT_EXPIRED${RESET}"
		fi
		creation_date=$(date -d "$not_before" +%Y-%m-%d)
		expiry_date=$(date -d "$not_after" +%Y-%m-%d)
		echo " (from $creation_date to $expiry_date)"
	else
		echo -ne "\t${RED}CERT_FILE_NOT_FOUND${RESET}"
	fi
else
	if [[ ! -d $ovpn_path ]]; then
		echo "${RED}$ovpn_path does not exist${RESET}"
	fi
fi
