/*
 * dctpPthreadsMain.c -- Unix entry point for Pthreads port of dccp-tp
 *
 * Copyright (C) 2008 Tom Phelan
 *
 * This file is part of dccp-tp.
 *
 * Dccp-tp is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 2.1 of the License, or
 * (at your option) any later version.
 *
 * Dccp-tp 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 Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with dccp-tp.  If not, see <http://www.gnu.org/licenses/>.
 *
 * Documentation and source code for dccp-tp is available at
 * http://www.phelan-4.com/dccp-tp/.
 */

#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include "dctpCore.h"
#include "dctpSupport.h"

void echoServerInit(void);
void echoClientInit(void);

int main(int argc, char **argv) {
    int startEchoClient = 1;
    int startEchoServer = 1;
    int daemonize = 0;
    int optc;

    while ((optc = getopt(argc, argv, "scd")) > 0) {
	switch (optc) {
	case 's':
	    startEchoClient = 0;
	    startEchoServer = 1;
	    break;
	case 'c':
	    startEchoClient = 1;
	    startEchoServer = 0;
	    break;
	case 'd':
	    daemonize = 1;
	    break;
	default:
	    printf("Invalid option %c\n", optc);
	    return(-1);
	}
    }
    if (daemonize) {
	if (daemon(0, 0) < 0) {
	    printf("Can't run as daemon: %s\n", strerror(errno));
	    return(-1);
	}
	dctpoLog(DCTPLOG_INFO, "main: dccp-tp running as daemon, pid %d\n", getpid());
    }
    /* Start up dccp-tp */
    dctpoInit();
    /* Start up the echo server */
    if (startEchoServer) {
	dctpoLog(DCTPLOG_INFO, "main: starting echo-server\n");
	echoServerInit();
    }
    /* Give it time to init */
    sleep(3);
    /* Start up the echo client */
    if (startEchoClient) {
	dctpoLog(DCTPLOG_INFO, "main: starting echo-client\n");
	echoClientInit();
    }
    /* Let them do their things */
    while (1) {
	sleep(10);
    }
    return(0);
}

