#!/bin/bash

set -euo pipefail
. driglibash-base

if [ "$#" -lt 1 ] ; then
	die "Usage: $0 <service_nanme> [-v]"
fi
service="$1"
shift

verbose=false
if [ "$#" -ge 1 ] && [ "$1" = "-v" ] ; then
	verbose=true
fi

. /etc/jeancloud.env

# Look in both cert directories
for dir in "$dns_certs_path" "$http_certs_path" ; do
	name="$(ls "$dir" | grep "^$service\(-[0-9]\{4\}\)\?$")" || true
	if [ -z "$name" ] ; then
		if $verbose ; then
			echo "Service $service have no certificate in $dir" >&2
		fi
	elif [ ! -e "$dir/$name/fullchain.pem" ] ; then
		if $verbose ; then
			echo "Service $service have no cert in dir $dir" >&2
		fi
	else
		echo "$dir/$name"
		exit 0
	fi
done

# If nothing found, use dummy cert
echo "$dummy_cert_path"
