#!/bin/bash

# This is the path inside the ramdisk, referenced in config files
INSIDEDIR=/etc/ironic-python-agent.d/

# but when copying files from outside the ramdisk, we have to use the mounted
# DIB filesystems
KEYDIR=$TMP_BUILD_DIR/mnt/$INSIDEDIR

CONFFILE=$KEYDIR/10-configure-tls.conf
CACONFFILE=$KEYDIR/11-configure-client-cert-ca.conf

if [[ -z $DIB_IPA_CERT_FILE ]] && [[ -z $DIB_IPA_KEY_FILE ]]; then
    echo "Both DIB_IPA_CERT_FILE and DIB_IPA_KEY_FILE are not set; generating self-signed cert"
    sudo openssl req -new -nodes -newkey rsa:4096 -days ${DIB_IPA_CERT_EXPIRATION:-1095} -x509 -subj "/C=US/ST=NA/L=NA/O=NA/CN=${DIB_IPA_CERT_HOSTNAME:-ipa-ramdisk.example.com}" -keyout $KEYDIR/agent.key -out $KEYDIR/agent.crt
else
    sudo cp $DIB_IPA_CERT_FILE $KEYDIR/agent.crt
    sudo cp $DIB_IPA_KEY_FILE $KEYDIR/agent.key
fi

cat <<EOF | sudo tee $CONFFILE
[DEFAULT]
listen_tls = True
advertise_protocol = https

[ssl]
cert_file = $INSIDEDIR/agent.crt
key_file = $INSIDEDIR/agent.key
EOF

if [[ -n $DIB_IPA_CA_FILE ]]; then
    echo "DIB_IPA_CA_FILE set, configuring IPA to validate client certificates"
    sudo cp $DIB_IPA_CA_FILE $KEYDIR/agent.cacert.pem
    cat <<EOF | sudo tee $CACONFFILE
[ssl]
ca_file = $INSIDEDIR/agent.cacert.pem
EOF
fi