/*
 * cnx_date_srv.c
 *
 * Copyright (c) 2008 Luis Rei <luis.rei@gmail.com>
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use, copy,
 * modify, merge, publish, distribute, sublicense, and/or sell copies
 * of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 */

#include "mydate.h"

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#define BACKLOG 10		// a commonly used value in examples
#define MAXBUFSIZE 2048	// ought to be enough

int main(int argc, char *argv[]) {
	int sock, conn, port, status, childpid;
	unsigned int cli_size;
	char buf[MAXBUFSIZE];
	struct sockaddr_in saddr, cli_addr;
	char *endptr, *r, *tok;

	if (argc != 2) {
		printf("Usage: cnx_date_srv [port]\n");
		exit(0);
	}

	// verify that the port number is valid
	port = strtol(argv[1], &endptr, 0);
	if ( *endptr ) {
		fprintf(stderr, "Invalid port number.\n"), exit(0);
	}

	// Create the listening socket (TCP)
	sock = socket(PF_INET, SOCK_STREAM, IPPROTO_IP);
	if (sock < 0)
		perror("Error creating socket"), exit(0);

	// zero the sockaddr_in structure and fill in the values
	memset(&saddr, 0, sizeof(struct sockaddr_in));
	saddr.sin_family = AF_INET;
	saddr.sin_port = htons(port);
	saddr.sin_addr.s_addr = htonl(INADDR_ANY);

	// bind the socket
	status = bind(sock, (struct sockaddr *) &saddr,
			sizeof(struct sockaddr_in));
	if (status < 0)
		perror("Error binding socket to interface"), exit(0);

	// start listen()ing for connections
	status = listen(sock, BACKLOG);
	if (status < 0)
		perror("Error trying to listen()"), exit(0);

	// main loop: wait for requests and reply accordingly
	while (1) {
		cli_size = sizeof(cli_addr);
		// accept connections and get the client address (sockaddr)
		conn = accept(sock, (struct sockaddr *)&cli_addr, &cli_size);
		if (conn < 0)
			perror("Error trying to accept()"), exit(0);

		/*
		 * Fork the server to handle the connections
		 */
		if ((childpid = fork()) < 0) {
			perror("fork()");
			exit(0);
		}
		else if (childpid == 0) {
			/*
			 * child process - process client requests
			 */
			close(sock);

			// get the the message
			while (recv(conn, buf, MAXBUFSIZE-1, 0) > 0) {
				if (status < 0)
					perror("Error trying to recv()"), exit(0);

				printf("Server Received (from %s): %s\n",
						inet_ntoa(cli_addr.sin_addr), buf);

				tok = strtok(buf, " ");
				if (strcmp(tok, "DATE") == 0) {
					r = mygetdate();
					send(conn, r, strlen(r), 0);
				}
				else if (strcmp(tok, "ADJTIME") == 0) {
					tok = strtok(NULL, " ");
					if (tok != NULL) {
						r = myadjdate(atoi(tok));
						send(conn, r, strlen(r), 0);
					}
				}
				memset(buf, 0, MAXBUFSIZE-1);	// clear the buffer
			} // end of connection loop
			exit(0);
		} // end of child
		else {
			/*
			 * parent process - waits the child process to terminate
			 */
			if (waitpid(childpid, NULL, 0) != childpid)
				perror("waitpid");
			close(conn);
		}
	} // end of main loop

	// close socket
	close(sock);

	return 0;
}
