//
//  osxtads_random.m
//  XTads
//
//  Created by Rune Berg on 12/07/2020.
//  Copyright © 2020 Rune Berg. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "osxtads_support.h"


void xtads_gen_rand_bytes(unsigned char* buf, size_t len);

/* Get a suitable seed for a random number generator.
 */
void
os_rand( long* val )
{
	XTOSIFC_TRACE_ENTRY(@"os_rand");

	unsigned char* buf = (unsigned char*)val;
	size_t len = sizeof(val);
	xtads_gen_rand_bytes(buf, len);
}

/* Generate random bytes for use in seeding a PRNG (pseudo-random number
 * generator).
 */
void
os_gen_rand_bytes( unsigned char* buf, size_t len )
{
	XTOSIFC_DEF_SELNAME(@"os_gen_rand_bytes");
	XTOSIFC_TRACE_1(@"len=%d", len);

	xtads_gen_rand_bytes(buf, len);
}
	
void
xtads_gen_rand_bytes( unsigned char* buf, size_t len )
{
	// See https://developer.apple.com/library/mac/documentation/Security/Conceptual/cryptoservices/RandomNumberGenerationAPIs/RandomNumberGenerationAPIs.html#//apple_ref/doc/uid/TP40011172-CH12-SW2
	
	XTOSIFC_DEF_SELNAME(@"xtads_gen_rand_bytes");
	XTOSIFC_TRACE_1(@"len=%d", len);
	
	const char* devRandom = "/dev/random";
	
	FILE *fp = fopen(devRandom, "r");
	if (fp == NULL) {
		XTOSIFC_ERROR_1(@"failed to open %s for reading", devRandom);
		return;
	}
	
	int i;
	for (i = 0; i < len; i++) {
		int c = fgetc(fp);
		buf[i] = c;
		//XT_TRACE_1(@"c=%d", c);
	}
	
	fclose(fp);
}

