/* fileserver.c */

#include <stdlib.h>
#include <stdio.h>
#include <cnaiapi.h>
#include <sys/stat.h>
#include <unistd.h>

#define BUFFSIZE		256
#define INPUT_PROMPT		"Input   > "
#define RECEIVED_PROMPT		"Received> "

int recvln(connection, char *, int);
int readln(char *, int);

/*-----------------------------------------------------------------------
 *
 * Program: chatserver
 * Purpose: wait for a connection from a chatclient & allow users to chat
 * Usage:   chatserver <appnum>
 *
 *-----------------------------------------------------------------------
 */
int
main(int argc, char *argv[])
{
	connection	conn;
	int		laenge;
	char		buff[BUFFSIZE];
        FILE*           schreiben;
        char            filename[BUFFSIZE];
	struct stat	attrib;
	int 		empfangen;
	int		len;

	if (argc != 2) {
		(void) fprintf(stderr, "usage: %s <appnum>\n", argv[0]);
		exit(1);
	}

	(void) printf("File-Server Waiting For Connection.\n");

	/* wait for a connection from a fileclient */

	conn = await_contact((appnum) atoi(argv[1]));
	if (conn < 0)
		exit(1);
	
	(void) printf("File-Connection Established.\n");
	len = recvln(conn, filename, BUFFSIZE);

	filename[len-1] = 0;

	if ((schreiben = fopen (filename, "w")) == NULL)
	{
		perror ("Fehler beim Anlegen der Datei");
		exit(1);
	}

	recv(conn, &laenge, sizeof(int), 0);

	printf("Datei %s wird geschrieben.\n", filename);

	empfangen = 0;

	/* iterate, reading from the client and write to file */

	while(1) {
		if (empfangen >= laenge) break;
		len = recv(conn, buff, BUFFSIZE, 0);
		empfangen += len;
		printf ("%d von %d empfangen.\n", empfangen, laenge);
		fwrite(buff, sizeof(char), len, schreiben);
		fflush(schreiben);
	}

	/* iteration ends when EOF found on stdin or file connection */
	fclose(schreiben);

	(void) send_eof(conn);
	(void) printf("\nFile Connection Closed.\n\n");
	return 0;
}

