#!/bin/bash
# $Id: ovpn_list_sessions.bash 1037 2026-03-16 15:07:58Z bertrand $
# Ce script permet de lister les sessions en cours.
# external parameters
# internal parameters
RED=$(tput setaf 1)
GREEN=$(tput setaf 2)
YELLOW=$(tput setaf 3)
RESET=$(tput sgr0)
# ovpn
ovpn_status_path="/var/log/openvpn-status.log"
function format_timespan()
{
	elapsed_time=$1
	if [[ $elapsed_time -gt 86400 ]]; then
		let days=$elapsed_time/86400
		pattern="${days}d %Hh %Mm %Ss"
	else
		if [[ $elapsed_time -gt 3600 ]]; then
			pattern="%Hh %Mm %Ss"
		else
			if [[ $elapsed_time -gt 60 ]]; then
				pattern="%Mm %Ss"
			else
				pattern="%Ss"
			fi
		fi
	fi
	echo $(date -d@$elapsed_time -u +"$pattern")
}
if [[ -f $ovpn_status_path ]]; then
	#cat $ovpn_status_path | grep '^CLIENT_LIST' | cut -d, -f2
	datetime_now=$(date +%s)
	while read current_session; do
		session=$(echo $current_session | grep '^CLIENT_LIST')
		if [[ -n $session ]]; then
			client_name=$(echo $current_session | cut -d, -f2)
			remote_address=$(echo $current_session | cut -d, -f3)
			local_address=$(echo $current_session | cut -d, -f4)
			session_start=$(echo $current_session | cut -d, -f8)
			datetime_start=$(date -d "$session_start" +%s)
			elapsed_time=$(($datetime_now-$datetime_start))
			text_elpased_time=$(format_timespan $elapsed_time)
			echo "$client_name [$remote_address -> $local_address] since $session_start ($text_elpased_time)"
		fi
	done < $ovpn_status_path
else
	echo "${RED}$ovpn_status_path does not exist${RESET}"
fi
