#!/bin/sh -e

state="$( cat "$__object/explorer/state" )"

if [ "$state" = 'present' ]
then
    exit 0
fi

if [ -f "$__object/parameter/common-name" ]
then
    common_name="$( cat "$__object/parameter/common-name" )"
else
    common_name="$__object_id"
fi

key_path="$( cat "$__object/parameter/key-path" )"

if echo "$key_path" | grep -Fq '%s'
then
    # shellcheck disable=SC2059
    key_path="$( printf "$key_path" "$__object_id" )"
fi

cert_path="$( cat "$__object/parameter/cert-path" )"

if echo "$cert_path" | grep -Fq '%s'
then
    # shellcheck disable=SC2059
    cert_path="$( printf "$cert_path" "$__object_id" )"
fi

key_type="$( cat "$__object/parameter/key-type" )"

key_type_arg="$( echo "$key_type" | cut -d : -f 2 )"

case "$key_type" in
    rsa:*)
        echo "openssl genrsa -out '$key_path' $key_type_arg"
    ;;
    ec:*)
        echo "openssl ecparam -name $key_type_arg -genkey -noout -out '$key_path'"
    ;;
esac

# shellcheck disable=SC2016
echo 'csr_path="$( mktemp )"'

echo "openssl req -new -subj '/CN=$common_name' -key '$key_path' -out \"\$csr_path\""

echo "openssl x509 -req -sha256 -days 3650 -in \"\$csr_path\" -signkey '$key_path' -out '$cert_path'"

# shellcheck disable=SC2016
echo 'rm -f "$csr_path"'

if [ "$( cat "$__object/explorer/ssl-cert-group" )" = 'present' ]
then
    key_group='ssl-cert'
else
    key_group='root'
fi

echo "chmod 640 '$key_path'"

echo "chown root '$key_path'"

echo "chgrp $key_group '$key_path'"

echo "chmod 644 '$cert_path'"

echo "chown root '$cert_path'"

echo "chgrp root '$cert_path'"
