/*
ardtalk.c - Part of ardcom - Easy communication over USB with Arduino
Copyright 2013 - Laurent Menu-Kerforn
    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, see <http://www.gnu.org/licenses/>.
*/
#include <string.h>
#include <errno.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>

#include "ardcom.h"
#include "mkfifo.h"
#include "mktools.c"

char sockfile[SLEN]=DEFAULTSOCKET;

/* ==========================================
             _       _   
 ___ ___  __| |_____| |_ 
(_-</ _ \/ _| / / -_)  _|
/__/\___/\__|_\_\___|\__|
                     
*/
void* sockaccess(char ope,char *message) {
	unsigned int fdclient;
	struct sockaddr_un sockclient;
	socklen_t soclen;
	char operation[3];
	ssize_t ret;
	size_t len;
	char *ptr=message;
	int stop=0;

	fdclient=socket(AF_UNIX, SOCK_STREAM, 0);
	if(fdclient<0) sysexitf("NOSOCK","Can't create socket");

	memset(&sockclient, 0, sizeof(struct sockaddr_un));
	sockclient.sun_family = AF_UNIX;  /* local is declared before socket() ^ */
	strcpy(sockclient.sun_path,sockfile);

	if(connect(fdclient,(struct sockaddr *)&sockclient,sizeof(struct sockaddr_un))<0)
		sysexitf("NOSOCK","Can't connect socket");

	switch(ope) {
		case 'r':
			strcpy(operation,"RX");
			break;
		case 't':
			strcpy(operation,"TX");
			break;
		default:
			strcpy(operation,"XX");
		};
	if((ret=send(fdclient,operation,strlen(operation),0))<=0)
		sysexitf("COM","Can't send operation");
		
	switch(ope) {
		case 'r':
			do {
				if((ret=recv(fdclient,ptr,1,0))<=0)
					sysexitf("COM","Can't receive");
				if(*ptr==(char)10) {*ptr=0;stop=1;};
				ptr++;
				// warnf("RECEIVE",message);	
				}
			while (!stop);
			// send(fdclient,"tagada",2,0); // eviter pb erreur sur RX ??
			puts(message);
			break;	
			
		case 't':
			len=strlen(message);
			message[len++]=(char)10;
			message[len]=(char)0;
			if((ret=send(fdclient,message,strlen(message),0))<=0)
				sysexitf("COM","Can't send message");
			break;
		default:
			break;
		};
	close(fdclient);
	}

//====================================
/* ==========================================
            _      
 _ __  __ _(_)_ _  
| '  \/ _` | | ' \ 
|_|_|_\__,_|_|_||_|
                   
*/
main(int argc,char **argv) {
int index;
int c;
int quit=0; 
opterr = 0; //pas de raitement par defaut des options inconnues
char tag[SLEN];
char operation[3];
char message[MKF_BIGSTRING] ;
char ope=(char)0;

while ((c=getopt(argc,argv,"hSs:")) != -1)
	switch (c)
	{
	case 's':
		strcpy(sockfile,optarg);
		break;
	case 'h':
		warnf("SYNT","Syntax : -h help -S (show socket filename) -s <socket file> <RX|TX> [message]");
		quit=1;
		break;
	case 'S' :
		printf("%s",DEFAULTSOCKET);
		quit=1;
		break;
	case '?':
		if(!quit) {
			sprintf(tag,"Incorrect option (%c), use -h for available options",optopt);
			errorf("SYNT",tag);
			quit=1;
			};
		break;
	default:
		errorf("SYNT","Good shot : Unreachable error.");
		quit=1;		
	};
if(quit) {fprintf(stderr,"\n"); return 1;};

//printf("%s",argv[index]);
index++;

if (argv[index]) {
	strncpy(operation,argv[index],2);
	operation[2]=(char)0;
	}
else exitf("SYNT","Missing operation");


if(!strcmp(operation,"RX")) ope='r';
if(!strcmp(operation,"TX")) ope='t';
if(!ope) exitf("SYNT","Incorrect operation");

if(ope=='t') {
	if(argv[++index]) {
		strncpy(message,argv[index],sizeof(message)-1);
		message[sizeof(message)-1]=(char)0;
		}
	else exitf("SYNT","Missing message to transmit");
	};

sockaccess(ope,message);

return 0;	
}

