#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <string.h>
#include <sys/wait.h>

#define BLCKSZ 8192

extern void runtest(unsigned long long blocks_total, char *filename);

int
main(int argc, char **argv)
{
	int	i;
	int	status;

	if (argc < 3)
	{
		fprintf(stderr, "not enough arguments\n");
		exit(1);
	}

	unsigned long long blocks_total = strtoull(argv[1], NULL, 0);

	for (i = 2; i < argc; ++i)
	{
		pid_t	pid = fork();

		if (pid == 0)
		{
			runtest(blocks_total, argv[i]);
			exit(0);
		}
		else if (pid < 0)
		{
			perror("fork");
			exit(1);
		}
	}

	while (wait(&status) >= 0)
		;
	sleep(1);

	return 0;
}

void 
runtest(unsigned long long blocks_total, char *filename)
{
	char	junk[BLCKSZ];

	memset(junk, 'J', BLCKSZ);

	time_t	t0 = time(NULL);
	int fd = open(filename, O_CREAT | O_TRUNC | O_WRONLY, 0600);
	if (fd < 0)
	{
		perror("open");
		exit(1);
	}

	time_t	t1 = time(NULL);
	unsigned long long blocks_written = 0;

	while (blocks_written < blocks_total)
	{
		int wc = write(fd, junk, BLCKSZ);

		if (wc != BLCKSZ)
		{
			fprintf(stderr, "wc = %d\n", wc);
			perror("write");
			exit(1);
		}
		++blocks_written;
	}

	time_t	t2 = time(NULL);
	if (fsync(fd) != 0)
	{
		perror("fsync");
		exit(1);
	}

	time_t	t3 = time(NULL);
	if (close(fd) != 0)
	{
		perror("close");
		exit(1);
	}

	time_t	t4 = time(NULL);
	printf("[%s] open: %u, write: %u, fsync: %u, close: %u, total: %u\n",
		   filename, t1 - t0, t2 - t1, t3 - t2, t4 - t3, t4 - t0);
}
