/*
 * Remote Laboratory FPGA Server
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * (c) 2012 Timothy Pearson
 * Raptor Engineering
 * http://www.raptorengineeringinc.com
 */

#include <stdio.h>                /* perror() */
#include <stdlib.h>               /* atoi() */
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>               /* read() */
#include <errno.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <fcntl.h>
#include <termios.h>
#include <unistd.h>
#include <sys/signal.h>
#include <sys/types.h>

#include <tqtimer.h>
#include <tqfile.h>

#include <tdelocale.h>

#include "sensor_conn.h"

#define ABORT_SOCKET(s) 		s->close();						\
					s->disconnect();					\
					delete s;						\
					s = NULL;

#define NETWORK_COMM_TIMEOUT_MS 5000

/* exception handling */
struct exit_exception {
	int c;
	exit_exception(int c):c(c) { }
};

enum connectionStates {
	StateIdle			= 0
};

/*
  The SensorSocket class provides a socket that is connected with a client.
  For every client that connects to the server, the server creates a new
  instance of this class.
*/
SensorSocket::SensorSocket(int sock, TQObject *parent, const char *name) :
	TDEKerberosServerSocket(parent, name), m_criticalSection(0), m_loopTimer(NULL), m_config(static_cast<SensorServer*>(parent)->m_config), m_commandLoopState(StateIdle)
{

	// Initialize timers
	m_kerberosInitTimer = new TQTimer();
	connect(m_kerberosInitTimer, SIGNAL(timeout()), this, SLOT(finishKerberosHandshake()));
	m_servClientTimeout = new TQTimer();
	
	// Initialize data structures
	int i;
	for (i=0;i<MAX_SENSORS;i++) {
		m_sensorMinIntervalTimers[i] = NULL;
	}

	initializeSensors();

	setServiceName("ulab");

	connect(this, SIGNAL(connectionClosed()), SLOT(connectionClosedHandler()));
	connect(this, SIGNAL(connectionClosed()), parent, SLOT(remoteConnectionClosed()));
	setSocket(sock);
}

SensorSocket::~SensorSocket() {
	for (int j=0;j<MAX_SENSORS;j++) {
		if (m_sensorMinIntervalTimers[j]) {
			m_sensorMinIntervalTimers[j]->stop();
			delete m_sensorMinIntervalTimers[j];
			m_sensorMinIntervalTimers[j] = NULL;
		}
	}
	if (m_servClientTimeout) {
		m_servClientTimeout->stop();
		delete m_servClientTimeout;
		m_servClientTimeout = NULL;
	}
	if (m_kerberosInitTimer) {
		m_kerberosInitTimer->stop();
		delete m_kerberosInitTimer;
		m_kerberosInitTimer = NULL;
	}
	if (m_loopTimer) {
		m_loopTimer->stop();
		delete m_loopTimer;
		m_loopTimer = NULL;
	}
}

void SensorSocket::close() {
	if (state() == TQSocket::Connected) {
		TDEKerberosServerSocket::close();
		connectionClosedHandler();
		TQTimer::singleShot(0, parent(), SLOT(remoteConnectionClosed()));
	}
}

void SensorSocket::connectionClosedHandler() {
	printf("[DEBUG] Connection from %s closed\n\r", m_remoteHost.ascii());

	if (m_criticalSection > 0) {
		throw exit_exception(-1);
	}
}

void SensorSocket::initiateKerberosHandshake() {
	setUsingKerberos(true);
	m_kerberosInitTimer->start(100, TRUE);
}

void SensorSocket::finishKerberosHandshake() {
	if (kerberosStatus() == TDEKerberosServerSocket::KerberosInitializing) {
		m_kerberosInitTimer->start(100, TRUE);
		return;
	}
	if (kerberosStatus() == TDEKerberosServerSocket::KerberosInUse) {
		m_config->setGroup("Security");
		TQString masterUser = m_config->readEntry("masteruser");
		TQString masterRealm = m_config->readEntry("masterrealm");
		if (masterRealm == "") {
			masterRealm = "(NULL)";
		}
		if ((m_authenticatedUserName != masterUser) || (m_authenticatedRealmName != masterRealm)) {
			printf("[DEBUG] Connection from %s closed due to authentication failure (attempted connection as user %s@%s)\n\r", m_remoteHost.ascii(), m_authenticatedUserName.ascii(), m_authenticatedRealmName.ascii());
			close();
			return;
		}

		setDataTimeout(NETWORK_COMM_TIMEOUT_MS);

		TQDataStream ds(this);
		ds.setPrintableData(true);
		ds << TQString("OK");
		writeEndOfFrame();

		enterCommandLoop();
		return;
	}
	else {
		printf("[DEBUG] Connection from %s closed due to Kerberos failure\n\r", m_remoteHost.ascii()); fflush(stdout);
		close();
		return;
	}
}

void SensorSocket::initializeSensors() {
	int i=0;
	m_sensorList.clear();
	m_sensorExecInfo.clear();
	m_config->setGroup("Sensors");
	TQStringList sensorNameList = m_config->readListEntry("active");
	for (TQStringList::Iterator it = sensorNameList.begin(); it != sensorNameList.end(); ++it) {
		TQString sensorName = *it;
		if (m_config->hasGroup(TQString("Sensor %1").arg(sensorName))) {
			SensorType st;
			m_config->setGroup(TQString("Sensor %1").arg(sensorName));
			st.index = i;
			st.name = sensorName;
			st.description = m_config->readEntry("name", i18n("<unknown>"));
			st.units = m_config->readEntry("units", i18n("<unknown>"));
			st.min = m_config->readDoubleNumEntry("minvalue", 0.0);
			st.max = m_config->readDoubleNumEntry("maxvalue", 1.0);
			st.mininterval = m_config->readDoubleNumEntry("mininterval", 1.0);
			st.nominalinterval = m_config->readDoubleNumEntry("nominalinterval", 10.0);
			m_sensorList.append(st);
			m_sensorExecInfo[i] = m_config->readEntry("exec", "echo 0 && exit");
			if (!m_sensorMinIntervalTimers[i]) m_sensorMinIntervalTimers[i] = new TQTimer();
			m_sensorMinIntervalTimers[i]->stop();
			printf("[DEBUG] Added new sensor %s at index %d\n\r", st.name.ascii(), st.index);
			i++;
		}
		else {
			printf("[WARNING] Unknown sensor %s specified in sensor list.  Ignoring...\n\r", sensorName.ascii());
		}
		if (i>=MAX_SENSORS) {
			printf("[WARNING] MAX_SENSORS (%d) exceeded.  Ignoring any additional sensor definitions...\n\r", MAX_SENSORS);
			break;
		}
	}
	for (int j=i;j<MAX_SENSORS;j++) {
		if (m_sensorMinIntervalTimers[j]) {
			m_sensorMinIntervalTimers[j]->stop();
			delete m_sensorMinIntervalTimers[j];
			m_sensorMinIntervalTimers[j] = NULL;
		}
	}
}

void SensorSocket::commandLoop() {
	bool transferred_data;

	m_criticalSection++;
	try {
		transferred_data = false;
		if (state() == TQSocket::Connected) {
			if (m_commandLoopState == StateIdle) {
				if (canReadLine()) {
					processPendingData();
				}
				if (canReadFrame()) {
					TQDataStream ds(this);
					ds.setPrintableData(true);
					TQString command;
					ds >> command;
					if (command == "SENSORS") {
						clearFrameTail();
						ds << m_sensorList;
						writeEndOfFrame();
					}
					else if (command == "SAMPLE") {
						TQ_UINT32 sensorIndex;
						ds >> sensorIndex;
						clearFrameTail();
						printf("[DEBUG] Requested sample from sensor at index %d\n\r", sensorIndex);
						if (sensorIndex >= m_sensorList.count()) {
							ds << TQString("NCK");
						}
						else if (m_sensorMinIntervalTimers[sensorIndex]->isActive()) {
							ds << TQString("DLY");
						}
						else {
							double sampleValue;
							bool commandSuccess = true;
							long long intervalMsec = (m_sensorList[sensorIndex].mininterval*1.0e3);
							m_sensorMinIntervalTimers[sensorIndex]->start(intervalMsec, TRUE);
							TQDateTime timestamp = TQDateTime::currentDateTime(TQt::UTC);
							TQString command = m_sensorExecInfo[sensorIndex];
							FILE* pipe = popen(command.ascii(), "r");
							if (!pipe) {
								commandSuccess = false;
							}
							else {
								char buffer[1024];
								TQString result = "";
								while(!feof(pipe)) {
									if (fgets(buffer, 1024, pipe) != NULL) {
										result += buffer;
									}
								}
								TQ_INT32 retcode = pclose(pipe);
								sampleValue = result.toDouble();
								if (retcode != 0) {
									commandSuccess = false;
								}
							}
							if (commandSuccess) {
								ds << TQString("ACK");
								ds << sampleValue;
								ds << timestamp;
							}
							else {
								ds << TQString("NCK");
							}
						}
						writeEndOfFrame();
					}
					else if (command == "PING") {
						clearFrameTail();
						ds << TQString("PONG");
						writeEndOfFrame();
					}
					else if (command == "RESET") {
						clearFrameTail();
						ds << TQString("RESET");
						writeEndOfFrame();
					}
					else {
						clearFrameTail();
						printf("[WARNING] Received unknown command %s from host %s\n\r", command.ascii(), m_remoteHost.ascii()); fflush(stdout);
						ds << TQString("NCK");
						writeEndOfFrame();
					}
					transferred_data = true;
				}
			}
		}
		m_criticalSection--;
		if (transferred_data) {
			if (m_loopTimer) m_loopTimer->start(0, TRUE);
		}
		else {
			if (m_loopTimer) m_loopTimer->start(100, TRUE);
		}
		return;
	}
	catch (...) {
		m_criticalSection--;
		return;
	}
}

int SensorSocket::enterCommandLoop() {
	m_commandLoopState = StateIdle;
	if (!m_loopTimer) {
		m_loopTimer = new TQTimer();
		connect(m_loopTimer, SIGNAL(timeout()), this, SLOT(commandLoop()));
	}
	if (m_loopTimer) m_loopTimer->start(0, TRUE);
	return 0;
}

/*
  The SensorServer class handles new connections to the server. For every
  client that connects, it creates a new SensorSocket -- that instance is now
  responsible for the communication with that client.
*/
SensorServer::SensorServer(TQObject* parent, int port, KSimpleConfig* config) :
	TQServerSocket( port, 1, parent ), m_config(config), m_numberOfConnections(0) {

	if ( !ok() ) {
		printf("[ERROR] Failed to bind to port %d\n\r", port);
		exit(1);
	}

	printf("[INFO] Server started on port %d\n\r", port); fflush(stdout);
}

SensorServer::~SensorServer() {
	//
}

void SensorServer::newConnection(int socket) {
	SensorSocket *s = new SensorSocket(socket, this);
	s->m_remoteHost = s->peerAddress().toString();
	printf("[DEBUG] New connection from %s\n\r", s->m_remoteHost.ascii());
	if (m_numberOfConnections > 0) {
		printf("[DEBUG] Connection from %s closed due to multiple access attempt\n\r", s->m_remoteHost.ascii());
		ABORT_SOCKET(s)
		return;
	}
	connect(s, SIGNAL(connectionClosed()), s, SLOT(deleteLater()));
	s->initiateKerberosHandshake();
	emit newConnect(s);
}

void SensorServer::remoteConnectionClosed() {
	m_numberOfConnections--;
}