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

#define BLOCK_SIZE 4096
#define BUF_LEN BLOCK_SIZE

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

int main () {

    int cfd, sfd, fd;
    int count;

    char buffer[BUF_LEN], filename[MAX_FILENAME_LENGTH];

    //create the fifo files
    if (mkfifo ("./server_write.fifo", 0777) == -1) {
	perror ("mkfifo()");
	exit (1);
    }
    if (mkfifo ("./client_write.fifo", 0777) == -1) {
	perror ("mkfifo()");
	exit (1);
    }

    //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_RDONLY)) == -1) {
	perror ("open()");
	exit (1);
    }

    if ((sfd = open (SERVER_WRITE_FILE, O_WRONLY)) == -1) {
	perror ("open()");
	exit (1);
    }
    printf ("sfd: %d\n", sfd);

    //read filename from client
    count = read (cfd, filename, MAX_FILENAME_LENGTH);
    if (count == -1) {
	perror ("read()");
	exit (1);
    }
    filename[count] = '\0';
    //open this file for reading
    fd = open (filename, O_RDONLY);
    if (fd == -1) {
	perror ("open()");
	exit (1);
    }

    //read and send to client
    while (1) {
	count = read (fd, buffer, BUF_LEN);
	if (count == -1) {
	    perror ("read()");
	    exit (1);
	}
	printf ("sfd: %d\n", sfd);
	if (write (sfd, buffer, count) < count) {
	    perror ("write()");
	    exit (1);
	}
	if (count < BUF_LEN)
	    break;
	else
	    continue;//haha
    }

    close (fd);
    close (sfd);
    close (cfd);
    
    unlink (SERVER_WRITE_FILE);
    unlink (CLIENT_WRITE_FILE);

    return 0;
}


