/* LFS modified to test read-only file systems.  Generates files */

#include <stdio.h>
#include <sys/types.h>
#include <sys/uio.h>
#include <unistd.h>
#include <stdlib.h>

#include "sys/stat.h"
#include <sys/timeb.h>
#include "fcntl.h"
#include "time.h"

static char buf[40960];
static char name[32];
static char *prog_name;

extern int errno;

int rand_fd = -1;


#define NDIR 100


static char dir[32];

void creat_dir()
{
    int i;

    umask(0);

    for (i = 0; i < NDIR; i++) {
        sprintf(dir, "d%d", i);
        mkdir(dir, 0777);
    }
}

void creat_test(int n, int size)
{
    int i;
    int r;
    int fd;
    int j;

    unsigned s, f;
    s = time(0);

    for (i = 0, j = 0; i < n; i ++) {

	sprintf(name, "d%d/g%d", j, i);

	if((fd = open(name, O_RDWR | O_CREAT | O_TRUNC, S_IRWXU)) < 0) {
	    printf("%s: create %d failed %d %d\n", prog_name, i, fd, errno);
	    exit(1);
	}


	if ((rand_fd != -1) && ((r = read(rand_fd, buf, size)) < 0)) {
	  printf("%s: read failed %d %d\n", prog_name, r, errno);
	  exit(1);
	}

	/* buf[random() % size] ^= random(); */

	if ((r = write(fd, buf, size)) < 0) {
	    printf("%s: write failed %d %d\n", prog_name, r, errno);
	    exit(1);
	}

	if ((r = close(fd)) < 0) {
	    printf("%s: close failed %d %d\n", prog_name, r, errno);
	}

	if ((i+1) % 100 == 0) j++;

    }

    /*    sync(fd); */
    f = time(0);
    printf("%s: creat took %d usec\n",  prog_name,  f - s);
}



int main(int argc, char *argv[])
{
    int n;
    int size;

    prog_name = argv[0];

    if (argc < 3 || argc > 4) {
	printf("%s: %s num size <rand>\n", prog_name, prog_name);
	exit(1);
    }

    n = atoi(argv[1]);
    size = atoi(argv[2]);

    printf("%s %d %d\n", prog_name, n, size);

    creat_dir();

    /* Use random data in files */
    if (argc == 4) {
      printf("Using yrandom source\n");
      if((rand_fd = open("/dev/urandom", O_RDONLY)) < 0) {
	printf("%s: create failed %d %d\n", prog_name, rand_fd, errno);
	exit(1);
      }      
    }

    creat_test(n, size);
    return 0;
}
