/*
 * chat.c
 * 
 * Copyright 2026 osboxes <osboxes@osboxes>
 * 
 * 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, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA 02110-1301, USA.
 * 
 * Chat con cola de mensaje, leyendo por tipo de mensaje
 */


#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <string.h>

struct mensaje {
	long mtype;       /* message type, must be > 0 */
	char m[100];  //texto chat a enviar
};

void hijo(int tipo);
void padre(int tipo);

int main(int argc, char **argv) {
	if ( argc != 3 ) {
		printf("Forma de Uso: $ ./char <tipo de mensaje a leer> <tipo de mensaje a escribir>\n");
		return 1;
	}
	pid_t pid = fork();
	switch(pid) {
		case 0:
			hijo(atoi(argv[1]));
			break;
		case -1:
			printf("Rayos! error en fork!\n");
			break;
		default:
			padre(atoi(argv[2]));
			wait(0);
	}
	return 0;
}

void hijo(int tipo) {
	int msgid = msgget(0xA,0);
	struct mensaje m;
	m.mtype=tipo; // tmb podria ser 0L y leeria secuencialmente de todos los tipos de cola
	int rc=0;
	do {
		rc = msgrcv(msgid,&m,100,tipo,0);
		if ( rc == 100 ) printf("%ld<%s\n",m.mtype,m.m);
		else           printf("Error en lectura! rc=%d\n",rc);
	} while(rc == 100 && strncmp(m.m,"chau",4) != 0 );
}

void padre(int tipo) {
	int msgid = msgget(0xA,0);
	struct mensaje m;
	do {
		m.mtype=tipo;
		printf("%ld>",m.mtype);
		fgets(m.m,100,stdin);
		m.m[strlen(m.m)-1]='\0';
		msgsnd(msgid,&m,100,0);
	} while(strncmp(m.m,"chau",4) != 0);
}
