#!/bin/bash
CERT="/etc/ssl/certs/cert.pem"
KEY="/etc/ssl/private/private.pem"

set -eu

#check if cert link exists
if [[ ! -e "${CERT}" ]]; then
   setman-log warning "Missing certificate"
   exit 1;
fi

cert_status="$(/usr/lib/lwr/http/certificate info)"
if [[ "${cert_status}" == 'Self-signed' ]]; then
    /usr/lib/lwr/http/certificate self-signed check
elif [[ "${cert_status}" == 'Uploaded' ]]; then
    /usr/lib/lwr/http/certificate uploaded check
    # if uploaded check passed, then `check` should return `OK` to prevent setman to call default.
    # Self signed-certificate will be regenerated here only if it is invalid. It's a bit odd, that certificate is
    # regenerated in `check`, but currently `uploaded` cert is active so it does not change too much.
    # If this workaround is not working, then separate package api implementation should be provided, possibly with a locking
    # mechanism built into `certificate` command.
    /usr/lib/lwr/http/certificate self-signed regenerate --if-needed --offline
else
    setman-log error "Invalid cert status: ${cert_status}"
    exit 2
fi
