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

#define FIFO_FILE_READ "fifo_file_read"
#define FIFO_FILE_WRITE "fifo_file_write"
#define BLOCK_SIZE 4096
#define BUF_LEN BLOCK_SIZE

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

    int ffr, ffw, len, fd;
    char buf[BUF_LEN];

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

    ffr = open (FIFO_FILE_READ, O_RDONLY);
    if (ffr == -1) {
	perror ("open()");
	exit (1);
    }

    ffw = open (FIFO_FILE_WRITE, O_WRONLY);
    if (ffw == -1) {
	perror ("mkfifo()");
	exit (1);
    }

    //send filename to the fifo file for the server to read.
    if (write (ffw, argv[1], strlen (argv[1])) < strlen(argv[1])) {
	perror ("write()");
	exit (1);
    }
    close (ffw);

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

    //now read the file contents from the fifo file.
    while (1) {
	len = read (ffr, buf, BUF_LEN);
	if (len == -1) {
	    perror ("read()");
	    exit (1);
	}

	if (write (fd, buf, len) < len) {
	    perror ("write()");
	    exit (1);
	}

	//if len < BUF_LEN, nothing more to read
	if (len < BUF_LEN) {
	    close (fd);
	    exit (0);
	}
	else
	    continue; // ha ha
    }

    return 0;
}


