#!/bin/bash
set +x
generate_certificate() {
    #Create BMC SEL rotation file if not existing already
    touch /var/log/bmc_sel.log

    echo "+++++++++++++++Generating default certificates and private keys++++++++++++++++"
    # Generate PKI keys and certificate for NVSM APIs to work out of the box.
    # For proper security, admin must provide its own key & certificate via configuration file
    CA_FILES="/etc/nvsm/nvsm-ca"
    SERVER_FILES="/etc/nvsm/nvsm-server"
    (umask 077
    #Step 1: Generate a CA certificate
            openssl req -new -newkey rsa:2048 -nodes -x509 -days 3650 -sha256       \
                    -keyout ${CA_FILES}.key -out ${CA_FILES}.crt                    \
                    -subj "/C=XX/ST=XX/L=XXXX/O=XX XX/OU=X/CN=`hostname`"
    #Step 2: Generate a child certificate for nvsm microservices to use             \
            openssl req -new -newkey rsa:2048 -nodes -days 3650 -sha256             \
                    -keyout ${SERVER_FILES}.key -out ${SERVER_FILES}.csr            \
                    -subj "/C=XX/ST=XX/L=XXXX/O=XX XX/OU=X/CN=127.0.0.1"
    #Step 3: Sign the cert of step 2 with cert from step 1                          \
            openssl x509 -req -CAcreateserial -days 3650                            \
                    -CA ${CA_FILES}.crt -CAkey ${CA_FILES}.key                      \
                    -in ${SERVER_FILES}.csr -out ${SERVER_FILES}.crt
    )

}
SCRIPTDIR="/usr/share/nvsm/pkgscripts"
logger "$0" "$1" 
case "$1" in
    "pip-install")
        pip3 install certifi > /dev/null 2>&1
        ;;
    "pip-install")
        pip3 install certifi > /dev/null 2>&1
        ;;
    "configure")
        if [ ! -f "/etc/nvsm/nvsm-server.key" ]; then
            generate_certificate

            # Disable mosquitto in case of new installation of NVSM
            if [ "$(systemctl is-active mosquitto)" == "active" ] ; then
                systemctl stop mosquitto
                systemctl disable mosquitto
            fi
        fi

        #Request systemd to reload the unit files afresh
        systemctl daemon-reload
        dmidecode -s system-product-name | grep 'BlueField SoC'
        if [ "$?" -eq "0" ]; then
            systemctl start set_emu_param
            systemctl start mlx_ipmid.service
        fi

        systemctl enable nvsm
        systemctl enable nvsm-mqtt
        systemctl enable nvsm-core
        systemctl enable nvsm-api-gateway
        systemctl enable nvsm-notifier

        # final step, restart nvsm
        systemctl restart nvsm
        ;;
    "generatecertificate")
        if [ ! -f "/etc/nvsm/nvsm-server.key" ]; then
            generate_certificate
        fi
        ;;
    *)
        ;;
esac


