#!/bin/sh

set -eu

APPDIR=/usr/share/rekono
CONFDIR=/etc/rekono
RUNTIME=/run/rekono

install -d -o root   -g root   -m 0751 "${RUNTIME}"
install -d -o rekono -g rekono -m 0750 "${RUNTIME}/nginx" "${RUNTIME}/backend"
install -o root -g rekono -m 0664 /dev/null "${RUNTIME}/progress"

# Create symlink of config.yaml from configuration directory to Rekono home
if [ ! -e "${CONFDIR}/config.yaml" ]; then
    if [ -f "${REKONO_HOME}/config.yaml" ] && [ ! -L "${REKONO_HOME}/config.yaml" ]; then
        echo "Moving the configuration to ${CONFDIR}/config.yaml"
        mv "${REKONO_HOME}/config.yaml" "${CONFDIR}/config.yaml"
    else
        echo "Installing the default configuration in ${CONFDIR}/config.yaml"
        install -o rekono -g rekono -m 0640 "${APPDIR}/config.yaml" "${CONFDIR}/config.yaml"
    fi
fi
if [ ! -L "${REKONO_HOME}/config.yaml" ]; then
    rm -f "${REKONO_HOME}/config.yaml"
    ln -s "${CONFDIR}/config.yaml" "${REKONO_HOME}/config.yaml"
fi

# Initialize TLS self-signed certificates
if [ -d "${REKONO_HOME}/tls" ] && [ ! -e "${CONFDIR}/tls" ]; then
    echo "Moving the TLS certificate to ${CONFDIR}/tls"
    mv "${REKONO_HOME}/tls" "${CONFDIR}/tls"
fi
if [ ! -e "${CONFDIR}/tls/certificate.crt" ]; then
    echo "Generating a self-signed TLS certificate for 127.0.0.1"
    install -d -o rekono -g rekono -m 0750 "${CONFDIR}/tls"
    openssl req -x509 -nodes -days 3650 -newkey rsa:4096 -sha512 \
        -keyout "${CONFDIR}/tls/privatekey.key" \
        -out "${CONFDIR}/tls/certificate.crt" \
        -subj "/C=ES/O=Rekono/OU=Security/CN=localhost" \
        -addext "subjectAltName=DNS:localhost,IP:127.0.0.1,IP:::1"
    chown rekono:rekono "${CONFDIR}/tls/privatekey.key" "${CONFDIR}/tls/certificate.crt"
    chmod 0640 "${CONFDIR}/tls/privatekey.key"
    chmod 0644 "${CONFDIR}/tls/certificate.crt"
fi
