// Cliente de prueba: manda un mensaje desde un puerto de origen elegido y espera la respuesta.
//   demux_client <tcp|udp|udp-connect> <ip> <puerto> <puerto_origen> <mensaje> [espera_s]
// Con espera_s, la conexión se queda abierta ese tiempo después de la respuesta.
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <unistd.h>

#define REPLY_WAIT_S 2

int main(int argc, char *argv[]) {
    if (argc != 6 && argc != 7) {
        fprintf(stderr, "uso: %s <tcp|udp|udp-connect> <ip> <puerto> <puerto_origen> <mensaje> [espera_s]\n",
                argv[0]);
        return EXIT_FAILURE;
    }
    int is_tcp = strcmp(argv[1], "tcp") == 0;
    int is_connected = is_tcp || strcmp(argv[1], "udp-connect") == 0;
    if (!is_tcp && !is_connected && strcmp(argv[1], "udp") != 0) {
        fprintf(stderr, "protocolo no válido: %s\n", argv[1]);
        return EXIT_FAILURE;
    }
    int port = atoi(argv[3]);
    int source_port = atoi(argv[4]);
    if (port <= 0 || port > 65535 || source_port <= 0 || source_port > 65535) {
        fprintf(stderr, "puerto fuera de rango\n");
        return EXIT_FAILURE;
    }
    struct sockaddr_in remote;
    memset(&remote, 0, sizeof remote);
    remote.sin_family = AF_INET;
    remote.sin_port = htons((uint16_t)port);
    if (inet_pton(AF_INET, argv[2], &remote.sin_addr) != 1) {
        fprintf(stderr, "dirección no válida: %s\n", argv[2]);
        return EXIT_FAILURE;
    }

    int fd = socket(AF_INET, is_tcp ? SOCK_STREAM : SOCK_DGRAM, 0);
    if (fd == -1) {
        perror("socket");
        return EXIT_FAILURE;
    }
    int yes = 1;
    if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof yes) == -1) {
        perror("setsockopt");
        return EXIT_FAILURE;
    }
    struct timeval wait = {.tv_sec = REPLY_WAIT_S};
    if (setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &wait, sizeof wait) == -1) {
        perror("setsockopt");
        return EXIT_FAILURE;
    }
    struct sockaddr_in local;
    memset(&local, 0, sizeof local);
    local.sin_family = AF_INET;
    local.sin_addr.s_addr = htonl(INADDR_ANY);
    local.sin_port = htons((uint16_t)source_port);
    if (bind(fd, (struct sockaddr *)&local, sizeof local) == -1) {
        perror("bind");
        return EXIT_FAILURE;
    }
    if (is_connected && connect(fd, (struct sockaddr *)&remote, sizeof remote) == -1) {
        perror("connect");
        return EXIT_FAILURE;
    }
    size_t length = strlen(argv[5]);
    ssize_t sent = is_connected
        ? send(fd, argv[5], length, 0)
        : sendto(fd, argv[5], length, 0, (struct sockaddr *)&remote, sizeof remote);
    if (sent == -1) {
        perror("send");
        return EXIT_FAILURE;
    }
    char reply[256];
    ssize_t got = recv(fd, reply, sizeof reply - 1, 0);
    if (got == -1) {
        perror("recv");
        return EXIT_FAILURE;
    }
    reply[got] = '\0';
    printf("%s\n", reply);
    if (fflush(stdout) == EOF) {
        perror("fflush");
    }
    if (argc == 7) {
        unsigned rest = (unsigned)atoi(argv[6]);
        while (rest > 0) {
            rest = sleep(rest);
        }
    }
    if (close(fd) == -1) {
        perror("close");
        return EXIT_FAILURE;
    }
    return EXIT_SUCCESS;
}
