/*
 * Copyright (c) 2015-2016, Sumio Morioka
 * All rights reserved.
 *
 * This source code was originally written by Dr.Sumio Morioka for use in the 2015-2016 issues of 
 * "the Interface magazine", published by CQ publishing Co.Ltd in Japan (http://www.cqpub.co.jp).
 * The author has no responsibility on any results caused by using this code.
 *
 * - Author: Dr.Sumio Morioka (http://www002.upp.so-net.ne.jp/morioka, FB:Sumio Morioka)
 *
 *
 * IMPORTANT NOTICE:
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *   * Neither the name of the copyright holder nor the
 *     names of its contributors may be used to endorse or promote products
 *     derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <arpa/inet.h>
#include <errno.h>
#include <fcntl.h>
#include <getopt.h>
#include <libwebsockets.h>
#include <linux/i2c-dev.h>
#include <math.h>
#include <memory.h>
#include <netdb.h>
#include <netinet/in.h>
#include <pthread.h>
#include <semaphore.h>
#include <signal.h>
#include <sysexits.h>
#include <syslog.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <termios.h>
#include <time.h>
#include <unistd.h>

#define	HUB_SOCKET_PORT		9002
#define	HUB_MAX_CLIENT_NUM	4

typedef struct _hub_pict_buf {
	volatile char		valid_flag;			// NOTE: use volatile
	volatile char		validdata_flag;		// NOTE: use volatile
	volatile char		newdata_flag;		// NOTE: use volatile
} HUB_PICTBUF;

HUB_PICTBUF	hub_pf[HUB_MAX_CLIENT_NUM];		// use this (global)


void dispip(FILE *fp, char *ipaddr)
{
	char disp_ipaddr[4];
	bcopy(ipaddr,disp_ipaddr,4);
	fprintf(fp, "%u.%u.%u.%u",
				(u_char)disp_ipaddr[0],
				(u_char)disp_ipaddr[1],
				(u_char)disp_ipaddr[2],
				(u_char)disp_ipaddr[3]
			);
}


int init_hub_socket(char *hostname, int port, int max_client)
{
	int					sock;
	struct sockaddr_in	addr;
	struct hostent		*hub_host;

	// socket
	if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
		fprintf(stderr, "HUB: failed socket()\n");
		return -1;
	}

	// get IP addr
	if ((hub_host = gethostbyname(hostname)) == NULL) {
		fprintf(stderr, "HUB: failed gethostbyname(%s)\n", hostname);
		return -1;
	}

	// bind
	bzero((char *)(&addr), sizeof (addr));	// init structure
	addr.sin_family	= AF_INET;
	addr.sin_port	= htons(port);
//	inet_aton(ip_addr, &addr.sin_addr);
	bcopy(hub_host->h_addr, (char *)(&addr.sin_addr), hub_host->h_length);

	if (bind(sock, (const struct sockaddr *)(&addr), sizeof (addr)) == -1) {
		fprintf(stderr, "HUB: failed bind()\n");
		return -1;
	}

	// listen
	if (listen(sock, max_client) == -1) {
		fprintf(stderr, "HUB: failed listen()\n");
		return -1;
	}

//	// set to NON-BLOCKING mode
//	u_long	tmp	= 1;
//	ioctl(sock, FIONBIO, &tmp);

	// set to timeout mode
//	struct timeval tv;
//	tv.tv_sec	= 30;
//	tv.tv_usec	= 0;
//	setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv, sizeof(tv));
//	setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, (char *)&tv, sizeof(tv))

	fprintf(stderr, "HUB: socket initialized [");
	dispip(stderr, hub_host->h_addr);
	fprintf(stderr, ":%d]\n", port);

	return sock;
}


// child thread for communicating with one client
void *host_func(void *param)
{
	int			fd, pbuf_id;
	HUB_PICTBUF	*pbuf;

	fd_set	sock_mask;
	char	wbuf;

	fd		= *((int *)param + 0);
	pbuf_id	= *((int *)param + 1);
	pbuf	= &(hub_pf[pbuf_id]);		// NOTE: pbuf->valid_flag == 1 at this moment

	FD_ZERO(&sock_mask);
	FD_SET(fd, &sock_mask);

	fprintf(stderr, "start host_thread (id %d, fd %d)\n", pbuf_id, fd);

	// send data request
	wbuf	= '#';
	write(fd, &wbuf, 1);

	while (1) {
//		int		ret;
//
//		// wait packet (no time-out)
//		if ((ret = select(fd + 1, &sock_mask, &sock_mask, NULL, NULL)) == -1) {	// error
//			fprintf(stderr, "error at select (%d)\n", fd);
//			break;
//		}
//		if (ret == 0)	// no packet
//			continue;
//
//		// check packet
//		if (FD_ISSET(fd, &sock_mask)) {
			char	ch;
			int		read_size;

			read_size	= read(fd, &ch, 1);
//			if (read_size == 0)	// socket was closed by client
			if (read_size < 1)	// socket was closed by client
				break;
			fprintf(stderr, "%c", ch);

			// send new data request
			wbuf	= '#';
			write(fd, &wbuf, 1);
//		}
	}

	pbuf->validdata_flag	= 0;
	pbuf->newdata_flag		= 0;
	pbuf->valid_flag		= 0;	// set this at the last

	fprintf(stderr, "end host_thread (id %d, fd %d)\n", pbuf_id, fd);

	close(fd);
	free(param);	// release parameter buffer created by parent
}


int main(int argc, char *argv[])
{
	int					cl;
	struct sockaddr_in	client_addr;
	socklen_t			client_addr_len;
	int					fd;
	pthread_t			th[HUB_MAX_CLIENT_NUM];

	if (argc < 2) {
		fprintf(stderr, "usage host ip_addr\n");
		exit(0);
	}

	// init info
	for (cl = 0; cl < HUB_MAX_CLIENT_NUM; cl++) {
		HUB_PICTBUF	*ptr;
		ptr	= &(hub_pf[cl]);

		ptr->valid_flag		= 0;
		ptr->validdata_flag	= 0;
		ptr->newdata_flag	= 0;
	}

	// generate socket
	int sock	= init_hub_socket(argv[1], HUB_SOCKET_PORT, HUB_MAX_CLIENT_NUM);
	if (sock == -1) {
		fprintf(stderr, "falied to init socket\n");
		return 0;
	}

	client_addr_len	= sizeof(client_addr);

	fprintf(stderr, "created hub_socket thread\n");

	while (1) {
		if ((fd = accept((u_short)sock, (struct sockaddr *)(&client_addr), &client_addr_len)) >= 0) {
			int			buf_id;

			// search empty buffer structure and then assign it
			for (buf_id = 0; buf_id < HUB_MAX_CLIENT_NUM; buf_id++) {
				HUB_PICTBUF	*ptr;
				ptr	= &(hub_pf[buf_id]);

				if (ptr->valid_flag == 0) {
					ptr->valid_flag		= 1;	// assign this
					ptr->validdata_flag	= 0;
					ptr->newdata_flag	= 0;

					int	*th_param	= (int *)malloc(sizeof (int) * 10);		// 10...max # of param
					// (the corresponding free() of th_param will be executed in client_func())
					*(th_param + 0)	= fd;
					*(th_param + 1)	= buf_id;
					pthread_create(&(th[buf_id]), NULL, host_func, (void *)th_param);
					break;
				}
			}
		}
	}

	return 0;
}

// end of file
