#!/bin/bash

. driglibash-base
. /etc/jeancloud.env

if [ "$#" -ne 2 ] || [ -z "$1" ] || [ -z "$2" ] ; then
	die "Usage: $0 <service-name> <action>"
fi

service="$1"
action="$2"

# Create dummy cert if needed
#TODO check if expired
if [ ! -f "$dummy_cert_path/privkey.pem" ] ; then
    echo "Dummy cert generation"
    run mkdir -p "$dummy_cert_path"
    run openssl req -x509 -newkey rsa:2048 -keyout "$http_certs_path/dummy/privkey.pem" -out "$http_certs_path/dummy/fullchain.pem" -days 365 -nodes -subj "/C=FR/ST=France/O=IT/CN=jean-cloud.net"
fi

if [ "$action" = add ] ; then
	# Link letsencrypt dir to dummy cert dir if there is no cert
	if [ ! -e "$certs_path/$service/fullchain.pem" ] ; then
	    section "Create cert dir"
	    run mkdir -p "$certs_path/$service"
	
	    section "Link dummy to cert"
	    run ln -s "$dummy_cert_path/fullchain.pem" "$certs_path/$service"
	    run ln -s "$dummy_cert_path/privkey.pem" "$certs_path/$service"
	fi
elif [ "$action" = remove ] ; then
	# UNlink letsencrypt dir to dummy cert dir IF it is the dummy cert
    if [ "$(readlink "$certs_path/$service_name/fullchain.pem")" = "$dummy_cert_path/fullchain.pem" ] ; then
        rm -r "$certs_path/$service_name"
    fi
else
	die "$0: Unknown action '$action'"
fi
