/*
 * copy a disk (or file) to many others.
 * usage: diskdup src tgt1 [tgt2 ...]
 */

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>

#define BS (1ul<<20)

char buf[BS];

ssize_t xwrite(int fd, char *buf, size_t blen)
{
  ssize_t rc, written = 0;

  while(blen) {
    rc = write(fd, buf, blen);
    if(rc < 0)
      return rc;
    buf = &buf[rc];
    blen -= rc;
    written += rc;
  }
  return written;
}

int main(int argc, char **argv)
{
  int fdin, *fdout;
  int i, rc, wrc, tgt = argc - 2;

  if(tgt < 1)
    return 0;
  
  fdout = malloc(sizeof(int) * tgt);

  fdin = open(argv[1], O_RDONLY);
  if(fdin == -1) {
    perror("open source");
    exit(1);
  }

  for(i = 0; i < tgt; i++) {
    fdout[i] = open(argv[i+2], O_WRONLY); 
    if(fdout[i] == -1) {
      fprintf(stderr, "unable to open %s, %m\n", argv[i+2]);
      exit(2);
    }
  }    
    
  while((rc = read(fdin, buf, BS)) > 0) {
    for(i = 0; i < tgt; i++) {
      if((wrc = xwrite(fdout[i], buf, rc)) != rc) {
	  fprintf(stderr, "write error tgt=%d rc=%d wrc=%d; %m\n",
		  tgt, rc, wrc);
	  exit(1);
      }
    }
  }
  
  if(rc != 0) {
    perror("huch on end");
  }
  exit(0);
}
  
  


