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

#define BLOCK_SIZE 4096
#define BUF_LEN BLOCK_SIZE

#define CLIENT_WRITE_FILE "client_write.fifo"
#define SERVER_WRITE_FILE "server_write.fifo"

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

    if (argc != 3) {
	fprintf (stderr, "Usage: %s remote_file local_file\n", argv[0]);
	exit (1);
    }

    int cfd, sfd, fd;
    int count;
    char buffer[BUF_LEN];

    //both server and client must open this file first, otherwise
    //it will form a deadlock. fifo's must be opened on both ends
    //otherwise the process opening the file first will block till
    //the other one opens it.
    if ((cfd = open (CLIENT_WRITE_FILE, O_WRONLY)) == -1) {
	perror ("open()");
	exit (1);
    }

    if ((sfd = open (SERVER_WRITE_FILE, O_RDONLY)) == -1) {
	perror ("open()");
	exit (1);
    }

    //write filename to server
    if (write (cfd, argv[1], strlen (argv[1])) < strlen (argv[1])) {
	perror ("write()");
	exit (1);
    }

    //now open file for writing
    if ((fd = open (argv[2], O_WRONLY|O_CREAT|O_TRUNC, 0777)) == -1) {
	    perror ("open()");
	    exit (1);
    }

    //start reading from the server
    while (1) {
	count = read (sfd, buffer, BUF_LEN);
	if (count == -1) {
	    perror ("read()");
	    exit (1);
	}
	if (write (fd, buffer, count) < count) {
	    perror ("write()");
	    exit (1);
	}
	if (count < BUF_LEN)
	    //nothing to read
	    break;
	else
	    continue; //haha
    }

    return 0;
}

