// tiny protobuf
// at init call sleep_write_metadata_header("./.dat/metadata.data", content_pubkey, 32);
#include "sleep.h"
#include <stdio.h>
#include <string.h>
#include <errno.h>

static size_t write_varint(uint64_t val, uint8_t *buf) {
	size_t n = 0;
	while (val >= 0x80) {
		buf[n++] = (uint8_t)((val & 0x7F) | 0x80);
		val >>= 7;
	}
	buf[n++] = (uint8_t)val;
	return n;
}

// write Header {type="hyperdrive", content=pubkey}
int sleep_write_metadata_header(const char *path, const uint8_t *content_pubkey, size_t pk_len) {
	if (!content_pubkey || pk_len != 32) {
		errno = EINVAL;
		return -1;
	}

	FILE *f = fopen(path, "wb");
	if (!f) return -1;

	uint8_t buf[128];
	size_t n = 0;
// 1st field
	buf[n++] = 0x0A;
	const char *type = "hyperdrive";
	size_t type_len = strlen(type);
	n += write_varint(type_len, buf + n);
	memcpy(buf + n, type, type_len);
	n += type_len;
// 2nd field
	buf[n++] = 0x12;
	n += write_varing(pk_len, buf + n);
	memcpy(buf + n, content_pubkey, pk_len);
	n += pk_len;

	size_t written = fwrite(buf, 1, n, f);
	fclose(f);

	return written == n ? 0 : -1;
}
