#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <Jonah.h>

void
notify(uint32 id, uint32 status)
{
	uint32 ret;
	uint32 foo;

	foo = status & 0xffff0000;
	if (foo == ObjStEECertIssued) {
		fprintf(stderr, "We got a CERT\n");
	} else {
		fprintf(stderr, "Notify: ID=%d\tSTATUS=%0x\n", id, status);
	}
	return;
}

int
ReadMessage(char *filename, unsigned char **cp, int *len)
{
    FILE                                *fp = NULL;
    int                                 size = 0;
    unsigned char               *tp = NULL;


    if ((fp = fopen(filename, "rb")) == NULL) {
        fprintf(stderr, "Can not open %s\n", filename);
        return -1;
    }
    fseek(fp, 0L, SEEK_END);
    size = ftell(fp);
    rewind(fp);
    if (size < 2) {
        fprintf(stderr, "Message to small\n");
        return size;
    }
    if ((tp = (unsigned char *) malloc(size)) == NULL) {
        fprintf(stderr, "Out of memory\n");
        return -1;
    }
    memset(tp, 0, size);
    if (fread(tp, size, 1, fp) != 1) {
        fprintf(stderr, "Read Error!\n");
        return -1;
    }
    fclose(fp);
    *cp = tp;
    *len = size;
    return 0;
}

int
main(int argc, char *argv[]) 
{
	uint32 status = 0;
	uint32 id = 0;
	unsigned char	*buf;
	utf8String	msg;
	int		bufLen;
	int ch;

	if (ReadMessage("c:/temp/pre-reg.b64", &buf, &bufLen) != 0) {
		exit(-1);
	}

	msg = (utf8String) malloc(bufLen +1);
	memset(msg, 0, bufLen + 1);
	memcpy(msg, buf, bufLen);
	JNH_start_server(0);
	JNH_register_callback(&notify);
	status = JNH_preregister_user(msg, (utf8String) "", &id);
	status = JNH_reserve_object(id);
	status = JNH_set_certreq_privkey_EE(id, (utf8String) "id-dsa", 512);
	status = JNH_save_object(id);
	status = JNH_export_credential(id, (utf8String) "password", 
				       (utf8String) "PKCS12:C:/temp/foo.12");
	return 0;
}
