/*
 * Copyright (C) 2011 matt mooney <mfm@muteddisk.com>
 *               2005-2007 Takahiro Hirofuchi
 *
 * 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 2 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, see <http://www.gnu.org/licenses/>.
 */

#ifdef HAVE_CONFIG_H
#include "../config.h"
#endif

#define _GNU_SOURCE
#include <errno.h>
#include <unistd.h>
#include <netdb.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <time.h>

#include <sys/mman.h>
#include <fcntl.h> /* For O_* constants */ 


#ifdef HAVE_LIBWRAP
#include <tcpd.h>
#endif

#include <getopt.h>
#include <signal.h>
#include <poll.h>

#include "usbip_host_driver.h"
#include "usbip_common.h"
#include "usbip_network.h"
#include "aes.h"

#undef  PROGNAME
#define PROGNAME "usbipd"
#define MAXSOCKFD 20
#define SHR_MEM_SIZE 32

#define MAIN_LOOP_TIMEOUT 10

static const char usbip_version_string[] = PACKAGE_STRING;

static int *mem_shr=NULL;

static const char usbipd_help_string[] =
	"usage: usbipd [options]			\n"
	"	-D, --daemon				\n"
	"		Run as a daemon process.	\n"
	"						\n"
	"	-d, --debug				\n"
	"		Print debugging information.	\n"
	"						\n"
	"	-h, --help				\n"
	"		Print this help.		\n"
	"						\n"
	"	-v, --version				\n"
	"		Show version.			\n";

static void usbipd_help(void)
{
	printf("%s\n", usbipd_help_string);
}

static int recv_request_import(int sockfd)
{
	struct op_import_request req;
	struct op_common reply;
	struct usbip_exported_device *edev;
	struct usbip_usb_device pdu_udev;
	int found = 0;
	int error = 0;
	int rc;

	memset(&req, 0, sizeof(req));
	memset(&reply, 0, sizeof(reply));

	rc = usbip_net_recv(sockfd, &req, sizeof(req));
	if (rc < 0) {
		dbg("usbip_net_recv failed: import request");
		return -1;
	}
	PACK_OP_IMPORT_REQUEST(0, &req);

	dlist_for_each_data(host_driver->edev_list, edev,
			    struct usbip_exported_device) {
		if (!strncmp(req.busid, edev->udev.busid, SYSFS_BUS_ID_SIZE)) {
			info("found requested device: %s", req.busid);
			found = 1;
			break;
		}
	}

	if (found) {
		/* should set TCP_NODELAY for usbip */
		usbip_net_set_nodelay(sockfd);

		/* export device needs a TCP/IP socket descriptor */
		rc = usbip_host_export_device(edev, sockfd);
		if (rc < 0)
			error = 1;
	} else {
		info("requested device not found: %s", req.busid);
		error = 1;
	}

	rc = usbip_net_send_op_common(sockfd, OP_REP_IMPORT,
				      (!error ? ST_OK : ST_NA));
	if (rc < 0) {
		dbg("usbip_net_send_op_common failed: %#0x", OP_REP_IMPORT);
		return -1;
	}

	if (error) {
		dbg("import request busid %s: failed", req.busid);
		return -1;
	}

	memcpy(&pdu_udev, &edev->udev, sizeof(pdu_udev));
	usbip_net_pack_usb_device(1, &pdu_udev);

	rc = usbip_net_send(sockfd, &pdu_udev, sizeof(pdu_udev));
	if (rc < 0) {
		dbg("usbip_net_send failed: devinfo");
		return -1;
	}

	dbg("import request busid %s: complete", req.busid);

	return 0;
}

static int send_reply_devlist(int connfd)
{
	struct usbip_exported_device *edev;
	struct usbip_usb_device pdu_udev;
	struct usbip_usb_interface pdu_uinf;
	struct op_devlist_reply reply;
	int i;
	int rc;

	reply.ndev = 0;
	/* number of exported devices */
	dlist_for_each_data(host_driver->edev_list, edev,
			    struct usbip_exported_device) {
		reply.ndev += 1;
	}
	info("exportable devices: %d", reply.ndev);

	rc = usbip_net_send_op_common(connfd, OP_REP_DEVLIST, ST_OK);
	if (rc < 0) {
		dbg("usbip_net_send_op_common failed: %#0x", OP_REP_DEVLIST);
		return -1;
	}
	PACK_OP_DEVLIST_REPLY(1, &reply);

	rc = usbip_net_send(connfd, &reply, sizeof(reply));
	if (rc < 0) {
		dbg("usbip_net_send failed: %#0x", OP_REP_DEVLIST);
		return -1;
	}

	dlist_for_each_data(host_driver->edev_list, edev,
			    struct usbip_exported_device) {
		dump_usb_device(&edev->udev);
		memcpy(&pdu_udev, &edev->udev, sizeof(pdu_udev));
		usbip_net_pack_usb_device(1, &pdu_udev);

		rc = usbip_net_send(connfd, &pdu_udev, sizeof(pdu_udev));
		if (rc < 0) {
			dbg("usbip_net_send failed: pdu_udev");
			return -1;
		}

		for (i = 0; i < edev->udev.bNumInterfaces; i++) {
			dump_usb_interface(&edev->uinf[i]);
			memcpy(&pdu_uinf, &edev->uinf[i], sizeof(pdu_uinf));
			usbip_net_pack_usb_interface(1, &pdu_uinf);

			rc = usbip_net_send(connfd, &pdu_uinf,
					    sizeof(pdu_uinf));
			if (rc < 0) {
				dbg("usbip_net_send failed: pdu_uinf");
				return -1;
			}
		}
	}

	return 0;
}

unsigned long long get_uID(){
    char path[512];
    char *ptr;
    int f;
    unsigned long long serial=0;

    f = open("/proc/cpuinfo",O_RDONLY);
    if (f<=0)
        return serial;
    //f = open("/home/matus/Downloads/cpuinfo",O_RDONLY);
    read(f,path,512);
    ptr=strstr(path,"Serial");
    ptr=strstr(ptr,":");
    serial=strtoull(ptr+2,NULL,16);
    return serial;
}

static int recv_request_devlist(int connfd)
{
	struct op_devlist_request req;
	int rc;

	memset(&req, 0, sizeof(req));

	rc = usbip_net_recv(connfd, &req, sizeof(req));
	if (rc < 0) {
		dbg("usbip_net_recv failed: devlist request");
		return -1;
	}

	rc = send_reply_devlist(connfd);
	if (rc < 0) {
		dbg("send_reply_devlist failed");
		return -1;
	}

	return 0;
}

static int recv_pdu(int connfd)
{
  	uint16_t code = OP_UNSPEC;
	int ret;
	char prikaz[16];
	char out[16];
	unsigned char expkey[4 * Nb * (Nr + 1)];
	char rovnake = 1;
	//unsigned char key[32];
	
	
	//memset(key,0x6A,16);
	
	ExpandKey ((unsigned char*)&mem_shr[10], expkey);
	srand((uint)time((time_t *)NULL));
	
	for (ret=0;ret<16;ret++)
	  prikaz[ret]=(char)rand();					//generovanie náhodného čísla
	Encrypt ((unsigned char*)prikaz, expkey, (unsigned char*)out);	//zašifrovanie čísla
	*(unsigned long long *)(out+16)=get_uID();
	usbip_net_send(connfd, out, 24);				//odoslanie zašifrovaného čísla 
	
	usbip_net_recv(connfd, out, 16);				//priate odšifrovaného čísla
	
	
	for (ret=0;ret<16;ret++)
	  if (out[ret]!=prikaz[ret])
	    rovnake=0;
	  if (rovnake==0){
	    strcpy(out,"NOK");
	    usbip_net_send(connfd, out, 3);	
	    close(connfd);
	    return 0;
	  }
	strcpy(out,"OK\0");
	usbip_net_send(connfd, out, 3);
	
	//DONE upravit ... odoslanie výzvy (nahodne generované číslo) (čaká na príjem zaheslovaného plus pridaný náhodný reťazec)
	//DONE v prípade správnej odpovede odošle OK a čaká na správu s príkazom. 
		
	
	ret = usbip_net_recv_op_common(connfd, &code);
	if (ret < 0) {
		dbg("could not receive opcode: %#0x", code);
		return -1;
	}

	ret = usbip_host_refresh_device_list();
	if (ret < 0) {
		dbg("could not refresh device list: %d", ret);
		return -1;
	}

	info("received request: %#0x(%d)", code, connfd);
	switch (code) {
	case OP_REQ_DEVLIST:
		ret = recv_request_devlist(connfd);
		break;
	case OP_REQ_IMPORT:
		ret = recv_request_import(connfd);
		break;
	case OP_REQ_DEVINFO:
	case OP_REQ_CRYPKEY:
	default:
		err("received an unknown opcode: %#0x", code);
		ret = -1;
	}

	if (ret == 0)
		info("request %#0x(%d): complete", code, connfd);
	else
		info("request %#0x(%d): failed", code, connfd);

	return ret;
}

#ifdef HAVE_LIBWRAP
static int tcpd_auth(int connfd)
{
	struct request_info request;
	int rc;

	request_init(&request, RQ_DAEMON, PROGNAME, RQ_FILE, connfd, 0);
	fromhost(&request);
	rc = hosts_access(&request);
	if (rc == 0)
		return -1;

	return 0;
}
#endif

static int do_accept(int listenfd)
{
	int connfd;
	struct sockaddr_storage ss;
	socklen_t len = sizeof(ss);
	char host[NI_MAXHOST], port[NI_MAXSERV];
	int rc;

	memset(&ss, 0, sizeof(ss));

	connfd = accept(listenfd, (struct sockaddr *) &ss, &len);
	if (connfd < 0) {
		err("failed to accept connection");
		return -1;
	}

	rc = getnameinfo((struct sockaddr *) &ss, len, host, sizeof(host),
			 port, sizeof(port), NI_NUMERICHOST | NI_NUMERICSERV);
	if (rc)
		err("getnameinfo: %s", gai_strerror(rc));

#ifdef HAVE_LIBWRAP
	rc = tcpd_auth(connfd);
	if (rc < 0) {
		info("denied access from %s", host);
		close(connfd);
		return -1;
	}
#endif
	info("connection from %s:%s", host, port);

	return connfd;
}

int process_request(int listenfd)
{
	pid_t childpid;
	int connfd;

	connfd = do_accept(listenfd);
	if (connfd < 0)
		return -1;
	childpid = fork();
	if (childpid == 0) {
		close(listenfd);
		recv_pdu(connfd);
		exit(0);
	}
	close(connfd);
	return 0;
}

static void log_addrinfo(struct addrinfo *ai)
{
	char hbuf[NI_MAXHOST];
	char sbuf[NI_MAXSERV];
	int rc;

	rc = getnameinfo(ai->ai_addr, ai->ai_addrlen, hbuf, sizeof(hbuf),
			 sbuf, sizeof(sbuf), NI_NUMERICHOST | NI_NUMERICSERV);
	if (rc)
		err("getnameinfo: %s", gai_strerror(rc));

	info("listening on %s:%s", hbuf, sbuf);
}

static int listen_all_addrinfo(struct addrinfo *ai_head, int sockfdlist[])
{
	struct addrinfo *ai;
	int ret, nsockfd = 0;


	struct sockaddr_in dest; 

	memset(&dest, 0, sizeof(dest));
   	dest.sin_family = AF_INET;
  	dest.sin_addr.s_addr = INADDR_ANY; 	/* set destination IP number - ALL ADRESES*/
	//dest.sin_addr.s_addr = htonl(INADDR_LOOPBACK); /* set destination IP number - localhost, 127.0.0.1*/ 
   	
	dest.sin_port = htons(USBIP_PORT);                /* set destination port number */

	for (ai = ai_head; ai && nsockfd < MAXSOCKFD; ai = ai->ai_next) {
		sockfdlist[nsockfd] = socket(ai->ai_family, ai->ai_socktype,
					     ai->ai_protocol);
		if (sockfdlist[nsockfd] < 0)
			continue;

		usbip_net_set_reuseaddr(sockfdlist[nsockfd]);
		usbip_net_set_nodelay(sockfdlist[nsockfd]);

		if (sockfdlist[nsockfd] >= FD_SETSIZE) {
			close(sockfdlist[nsockfd]);
			sockfdlist[nsockfd] = -1;
			continue;
		}

		//struct sockaddr *serverptr = (struct sockaddr*)&loopback; 
		//ret = bind(sockfdlist[nsockfd], ai->ai_addr, ai->ai_addrlen);
		ret = bind(sockfdlist[nsockfd], (struct sockaddr *)&dest, sizeof(struct sockaddr));
		if (ret < 0) {
			close(sockfdlist[nsockfd]);
			sockfdlist[nsockfd] = -1;
			continue;
		}

		ret = listen(sockfdlist[nsockfd], SOMAXCONN);
		if (ret < 0) {
			close(sockfdlist[nsockfd]);
			sockfdlist[nsockfd] = -1;
			continue;
		}

		log_addrinfo(ai);
		nsockfd++;
	}

	if (nsockfd == 0)
		return -1;

	dbg("listening on %d address%s", nsockfd, (nsockfd == 1) ? "" : "es");

	return nsockfd;
}

static struct addrinfo *do_getaddrinfo(char *host, int ai_family)
{
	struct addrinfo hints, *ai_head;
	int rc;

	memset(&hints, 0, sizeof(hints));
	hints.ai_family   = ai_family;
	hints.ai_socktype = SOCK_STREAM;
	hints.ai_flags    = AI_PASSIVE;
	//hints.ai_flags    = INADDR_LOOPBACK; 

	rc = getaddrinfo(host, USBIP_PORT_STRING, &hints, &ai_head);
	if (rc) {
		err("failed to get a network address %s: %s", USBIP_PORT_STRING,
		    gai_strerror(rc));
		return NULL;
	}

	return ai_head;
}

static void signal_handler(int i)
{
	dbg("received '%s' signal", strsignal(i));
}

static void signal_handler2(int i)
{
	dbg("received '%s' signal", strsignal(i));
}

static void set_signal(void)
{
	struct sigaction act;

	memset(&act, 0, sizeof(act));
	act.sa_handler = signal_handler;
	sigemptyset(&act.sa_mask);
	sigaction(SIGTERM, &act, NULL);
	sigaction(SIGINT, &act, NULL);
	act.sa_handler = signal_handler2;
	sigaction(SIGIO, &act, NULL);
	act.sa_handler = SIG_IGN;
	sigaction(SIGCLD, &act, NULL);
}

/*
static int over(int * confd){
  *confd=0;
  return 0;
};

static int pripoj_a_over(int * confd){
  int res=0;
  
  res=over(confd);
  return res;
}
*/
static int open_shr_memory(int** shr_mem){ 
	int Com_str;
      
	Com_str = shm_open("/_USB_IP_SHR_MEM_", O_CREAT | O_RDWR ,S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP| S_IROTH | S_IWOTH);
	if (Com_str == -1)
	{
	    dbg("Nepodarilo sa vytvorit zdielaný zdroj\n\r");
	    return -1;
	}

	if (ftruncate(Com_str, SHR_MEM_SIZE) == -1)
	{
	    dbg("Nepodarilo sa vytvorit Velkosť pre zdielaný zdroj\n\r");
	    return -1;
	}   /* Handle error */;


	/* Map shared memory object */
	*shr_mem= (int*)mmap(NULL, SHR_MEM_SIZE, PROT_READ | PROT_WRITE,
		      MAP_SHARED , Com_str, 0);
	dbg("Uspesne vytvorena zdielana pamat");
	
  return 0;
}
static int close_shr_memory(int** shr_mem){
  if (*shr_mem==NULL)
    return -1;
  munmap(*shr_mem,SHR_MEM_SIZE);
  dbg("zavreta zdielana pamat");
  return 0;
}


static int do_standalone_mode(int daemonize)
{
	
	struct addrinfo *ai_head;
	int sockfdlist[MAXSOCKFD];
	int nsockfd;
	int i, terminate,cpid;
	struct pollfd *fds;
	struct timespec timeout;
	sigset_t sigmask;
	//nacitanie hesla
	FILE *stream;
        size_t len = 0;
        ssize_t read;
	char *line = NULL;
	
	
	//uchar key[16];
	//uchar expkey[4 * Nb * (Nr + 1)];
	//ExpandKey (key, expkey);
	
	
	
	// otvorenie zdielanej pamäte
	i=open_shr_memory(&mem_shr);
	if (i!=0)
	{
	    err("CHYBA pri vytvarani zdielanej pamate");
	    return -1; 
	}
     //*********** NACITANIE HESLA SO SUBORU **********

           stream = fopen("/home/pi/usbip_linux/userspace/src/config.pass", "r");
           if (stream == NULL){
	       err("CHYBA pri otvarani suboru");
               return -1;
	     
	  }
	   
           while ((read = getline(&line, &len, stream)) != -1) {
	       strncpy((char*)&mem_shr[10],line,32);
           }
	   free(line);
           fclose(stream);
	   dbg("HESLO:%s",(char*)&mem_shr[10]);
    //****END**** NACITANIE hesla SO SUBORU ****END****
	
	
	
	if (usbip_host_driver_open()) {
		err("please load " USBIP_CORE_MOD_NAME ".ko and "
		    USBIP_HOST_DRV_NAME ".ko!");
		return -1;
	}

	if (daemonize) {
		if (daemon(0, 0) < 0) {
			err("daemonizing failed: %s", strerror(errno));
			usbip_host_driver_close();
			return -1;
		}
		umask(0);
		usbip_use_syslog = 1;
	}
	set_signal();
	
	cpid=fork();
	
	if(cpid==0){
		ai_head = do_getaddrinfo(NULL, PF_UNSPEC);
		if (!ai_head) {
			usbip_host_driver_close();
			return -1;
		}

		info("starting " PROGNAME " (%s)", usbip_version_string);

		nsockfd = listen_all_addrinfo(ai_head, sockfdlist);
		if (nsockfd <= 0) {
			err("failed to open a listening socket");
			freeaddrinfo(ai_head);
			usbip_host_driver_close();
			return -1;
		}
		fds = calloc(nsockfd, sizeof(struct pollfd));
		for (i = 0; i < nsockfd; i++) {
			fds[i].fd = sockfdlist[i];
			fds[i].events = POLLIN;
		}
		timeout.tv_sec = MAIN_LOOP_TIMEOUT;
		timeout.tv_nsec = 0;

		sigfillset(&sigmask);
		sigdelset(&sigmask, SIGTERM);
		sigdelset(&sigmask, SIGINT);
		
			terminate = 0;
		while (!terminate) {
			int r;

			r = ppoll(fds, nsockfd, &timeout, &sigmask);
			info("PRIATY SIGNAL_STRT: %d",r);
			if (r < 0){
			  
				dbg("%s", strerror(errno));
				terminate = 1;
			} else if (r) {
				info("PRIATY SIGNAL %d",r);
				
				for (i = 0; i < nsockfd; i++) {
					if (fds[i].revents & POLLIN) {
					  info("IF splneny_vypis pollin %d",POLLIN);
					  dbg("read event on fd[%d]=%d",
						    i, sockfdlist[i]);
						process_request(sockfdlist[i]);
					}
					
					
				}
			} else
				dbg("heartbeat timeout on ppoll()");
		}
		free(fds);
		freeaddrinfo(ai_head);
	}
	else{
		
		//ZAPIS SVOJE ProcesID;
		mem_shr[9]= getpid();
		msync(mem_shr,SHR_MEM_SIZE,MS_INVALIDATE | MS_SYNC);
		//ZAPIS SVOJE ProcesID DONE;
		
		
		timeout.tv_sec = MAIN_LOOP_TIMEOUT;
		timeout.tv_nsec = 0;
		
		info("PPID: %d" , cpid);
		info("MOJE ID PRE SIGNAL: %d" , mem_shr[9]);
		sigfillset(&sigmask);
		
		terminate = 0;
		while (!terminate) {
			int r;
			r=sigtimedwait(&sigmask,NULL,&timeout);
			dbg("SIGWAIT_VLAKNO_2: %d",r);
			if (r == SIGTERM || r == SIGINT){
				dbg("%s", strerror(errno));
				terminate = 1;
			} else if (r == SIGIO){
				struct sockaddr_in dest;
				pid_t childpid;
				int connfd=0;
				char SERVER_ADDR[16];
				unsigned char* IP;
				//struct timeval timeout;      

				// TODO Vytvorenie pripojenia (client) a predanie toho socketu do funkcie ... confd bude socket ktorý sa predá ďalej,
				//ret=pripoj_a_over(&connfd);
				//if (ret!=0){
				    //zapis do pamäti error ... a ďalším vláknom odošle že nieje možné pripojiť.
				//    continue;
				//}
				// TODO následné pridanie kontroli hesla, prvý paket bude obsahovať ID zariadenia a jeho heslo ak sa nebude zhodovať
				// TODO zamietne žiadosť a vypne sa 
			  
				
				if ( (connfd = socket(AF_INET, SOCK_STREAM, 0)) < 0 )
				{
				    err("NEPODARILO_SA VYTVORIT_Socket");
				    continue;
				    //exit(errno);
				    //return -1;
				}
				
				IP=(unsigned char*)(mem_shr+16);
				sprintf(SERVER_ADDR,"%u.%u.%u.%u",IP[0],IP[1],IP[2],IP[3]);
				sprintf(SERVER_ADDR,"%u.%u.%u.%u",192,168,1,101);
				    /*---Initialize server address/port struct---*/
				bzero(&dest, sizeof(dest));
				dest.sin_family = AF_INET;
				dest.sin_port = htons(USBIP_PORT);
				
				if ( inet_aton(SERVER_ADDR, (struct in_addr*)&dest.sin_addr.s_addr) == 0 )
				{
				    err("ERROR_nepodaril sa inet_aton:%s",SERVER_ADDR);
				    continue;
				}
				    info("connecting");
				    /*---Connect to server---*/
				//	timeout.tv_sec = 10;
				//	timeout.tv_usec = 0;
				//if (setsockopt (sockfd, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout, sizeof(timeout)) < 0)
				//    printf("setsockopt failed\n"); 
				//if (setsockopt (sockfd, SOL_SOCKET, SO_SNDTIMEO, (char *)&timeout, sizeof(timeout)) < 0)
				//    printf("setsockopt failed\n"); 
				
				if ( connect(connfd, (struct sockaddr*)&dest, sizeof(dest)) != 0 )
				{
				    info("ERROR nepodarilo sa pripojit!!! na %s",SERVER_ADDR);
				    continue;
				    //exit(errno);
				    //return -1;
				}
				info("connected");
				childpid = fork();
				if (childpid == 0){
					recv_pdu(connfd);
					exit(0);
				}
				close(connfd);
				//dbg("SIGIO_SIGNAL");	
			}
			else{
				mem_shr[9]= getpid();
				msync(mem_shr,SHR_MEM_SIZE,MS_INVALIDATE | MS_SYNC);
				dbg("heartbeat timeout on ppoll()_vlakno2");
			}
		}
	}
	info("shutting down " PROGNAME);
	
	close_shr_memory(&mem_shr);
	usbip_host_driver_close();

	return 0;
}

int main(int argc, char *argv[])
{
	static const struct option longopts[] = {
		{ "daemon",  no_argument, NULL, 'D' },
		{ "debug",   no_argument, NULL, 'd' },
		{ "help",    no_argument, NULL, 'h' },
		{ "version", no_argument, NULL, 'v' },
		{ NULL,	     0,           NULL,  0  }
	};

	enum {
		cmd_standalone_mode = 1,
		cmd_help,
		cmd_version
	} cmd;

	int daemonize = 0;
	int opt, rc = -1;

	usbip_use_stderr = 1;
	usbip_use_syslog = 0;

	if (geteuid() != 0)
		err("not running as root?");

	cmd = cmd_standalone_mode;
	for (;;) {
		opt = getopt_long(argc, argv, "Ddhv", longopts, NULL);

		if (opt == -1)
			break;

		switch (opt) {
		case 'D':
			daemonize = 1;
			break;
		case 'd':
			usbip_use_debug = 1;
			break;
		case 'h':
			cmd = cmd_help;
			break;
		case 'v':
			cmd = cmd_version;
			break;
		case '?':
			usbipd_help();
		default:
			goto err_out;
		}
	}

	switch (cmd) {
	case cmd_standalone_mode:
		rc = do_standalone_mode(daemonize);
		break;
	case cmd_version:
		printf(PROGNAME " (%s)\n", usbip_version_string);
		rc = 0;
		break;
	case cmd_help:
		usbipd_help();
		rc = 0;
		break;
	default:
		usbipd_help();
		goto err_out;
	}

err_out:
	return (rc > -1 ? EXIT_SUCCESS : EXIT_FAILURE);
}
