#!/bin/bash
# Copyright Atomicorp, 2023
# All rights reserved

source /var/awp/etc/config
TARGET=/var/awp/etc/.ssl/awpweb_server
CERTDIR=/var/awp/etc/.ssl


# if the ${CERTDIR}/${AWPWEB_CERTIFICATE}.crt does not exist, return full path to ${AWPWEB_CERTIFICATE}.crt not found
if [ ! -f ${CERTDIR}/${AWPWEB_CERTIFICATE}.crt ]; then
	echo "Certificate ${CERTDIR}/${AWPWEB_CERTIFICATE}.crt not found"
	exit 1
fi

# if the ${CERTDIR}/${AWPWEB_CERTIFICATE}.key does not exist, return full path to ${AWPWEB_CERTIFICATE}.key not found
if [ ! -f ${CERTDIR}/${AWPWEB_CERTIFICATE}.key ]; then
	echo "Certificate ${CERTDIR}/${AWPWEB_CERTIFICATE}.key not found"
	exit 1
fi

# copy ${CERTDIR}/${AWPWEB_CERTIFICATE}.crt to ${TARGET}.crt
cp ${CERTDIR}/${AWPWEB_CERTIFICATE}.crt ${TARGET}.crt

# copy ${CERTDIR}/${AWPWEB_CERTIFICATE}.key to ${TARGET}.key
cp ${CERTDIR}/${AWPWEB_CERTIFICATE}.key ${TARGET}.key

systemctl restart awpd

# if the service awp-db is enabled, then restart it
if systemctl is-enabled awp-db >/dev/null 2>&1; then
    pushd /var/awp/contrib/db/ >/dev/null
        docker compose restart atomic-nginx
    popd >/dev/null
fi