#include <zephyr/logging/log.h>
#include <zephyr/net/tls_credentials.h>

#include <errno.h>
#include <stdbool.h>

#include "credentials.h"

LOG_MODULE_REGISTER(credentials, LOG_LEVEL_INF);

#ifndef TLS_CREDENTIAL_CLIENT_CERTIFICATE
#define TLS_CREDENTIAL_CLIENT_CERTIFICATE TLS_CREDENTIAL_SERVER_CERTIFICATE
#endif

static const unsigned char ca_cert[] = {
#include "ca-cert.inc"
0x00
};

#if !defined(CONFIG_MQTT_HELPER_SEC_TAG)
#error "CONFIG_MQTT_HELPER_SEC_TAG must be defined for TLS provisioning"
#endif

#ifdef client_cert
#error "client_cert symbol already defined"
#endif

#ifdef client_key
#error "client_key symbol already defined"
#endif

static const unsigned char client_cert[] = {
#include "client-cert.inc"
0x00
};

static const unsigned char client_key[] = {
#include "client-key.inc"
0x00
};

int mqtt_credentials_provision(void)
{
    static bool provisioned;
    int err;

    if (provisioned) {
        LOG_DBG("TLS credentials already provisioned, skipping");
        return 0;
    }

    LOG_INF("Adding CA certificate (%zu bytes) to sec tag %d",
            sizeof(ca_cert) - 1, CONFIG_MQTT_HELPER_SEC_TAG);
    err = tls_credential_add(CONFIG_MQTT_HELPER_SEC_TAG,
                             TLS_CREDENTIAL_CA_CERTIFICATE,
                             ca_cert, sizeof(ca_cert) - 1);
    if (err < 0 && err != -EEXIST) {
        LOG_ERR("Failed to add CA certificate (%d)", err);
        return err;
    }

    LOG_INF("Adding client certificate (%zu bytes)", sizeof(client_cert) - 1);
    err = tls_credential_add(CONFIG_MQTT_HELPER_SEC_TAG,
                             TLS_CREDENTIAL_CLIENT_CERTIFICATE,
                             client_cert, sizeof(client_cert) - 1);
    if (err < 0 && err != -EEXIST) {
        LOG_ERR("Failed to add client certificate (%d)", err);
        return err;
    }

    LOG_INF("Adding client private key (%zu bytes)", sizeof(client_key) - 1);
    err = tls_credential_add(CONFIG_MQTT_HELPER_SEC_TAG,
                             TLS_CREDENTIAL_PRIVATE_KEY,
                             client_key, sizeof(client_key) - 1);
    if (err < 0 && err != -EEXIST) {
        LOG_ERR("Failed to add client private key (%d)", err);
        return err;
    }

    provisioned = true;
    LOG_INF("TLS credentials provisioned (sec tag %d)", CONFIG_MQTT_HELPER_SEC_TAG);

    return 0;
}
