#include <stdio.h>

#include <openssl/asn1.h>
#include <openssl/rsa.h>
#include <openssl/err.h>
#include <openssl/ssl.h>
#include <openssl/pem.h>
#include <openssl/x509.h>
#include <openssl/x509v3.h>

/* External function declarations for our library */
RSA *readRSA(const char *);
X509_REQ *readCSR(const char *);
X509 *readCert(const char *);
X509 *signRequestWithCertificate(X509 *, X509_REQ *, RSA *);

int main(int argc, char **argv)
{
    X509 *cert = NULL, *newcert = NULL;
    X509_REQ *csr = NULL;
    RSA *key = NULL, *key2 = NULL, *key3 = NULL;

    printf("init'ing OpenSSL\n");

    CRYPTO_malloc_init();
    ERR_load_crypto_strings(); 
    OpenSSL_add_all_algorithms();

    printf("Trying to read test CA certificate...\n");
    cert = readCert("../tests/certs/ca1.pem");
    printf("cert = %p\n", cert);

    printf("Reading CSR...\n");
    csr = readCSR("../tests/csr/test2.csr");
    printf("csr = %p\n", csr);

    printf("Reading key...\n");
    key = readRSA("../tests/keys/private/7c51d0ac629a02cf64429bc8677428189c4be60d.key");
    printf("key = %p\n", key);

    printf("Trying to create new certificate...\n");
    newcert = signRequestWithCertificate(cert, csr, key);
    printf("newcert = %p\n", newcert);

    printf("Trying to get copies of the certificates public key...\n");
    printf("key object we created earlier is %p\n", key);
    {
        RSA *tmp = EVP_PKEY_get1_RSA(X509_get_pubkey(cert));
        key2 = RSAPublicKey_dup(tmp);
        printf("1st copy = %p\n", key2);
        key3 = RSAPublicKey_dup(tmp);
        printf("2nd copy = %p\n", key3);
    }

    RSA_free(key);
    X509_free(newcert);
    X509_REQ_free(csr);
    X509_free(cert);

//    if (key2 != key)
        RSA_free(key2);
    RSA_free(key3);

    return 0;
}

