// blast: abre una conexión TCP, envía bytes y la cierra.
//
//   blast <ip> <puerto> <bytes> [--chunk N] [--gap-ms N] [--nodelay] [--reply] [--abort]
//
// Con --chunk y --gap-ms, envía de a N bytes con una pausa entre cada write. Con --reply,
// cierra solo su sentido con shutdown y se queda leyendo lo que conteste el servidor. Con
// --abort, cierra con SO_LINGER en cero: el kernel envía RST en vez de FIN.
#define _POSIX_C_SOURCE 200809L
#include <arpa/inet.h>
#include <errno.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <time.h>
#include <unistd.h>

#define BUF_SIZE 65536

static void pause_ms(long ms) {
    struct timespec ts = {ms / 1000, (ms % 1000) * 1000000L};
    while (nanosleep(&ts, &ts) < 0) {
        if (errno != EINTR) {
            perror("nanosleep");
            exit(1);
        }
    }
}

// Lo que el servidor conteste después de nuestro FIN: el otro sentido sigue abierto.
static void read_reply(int fd) {
    char reply[256];
    ssize_t got;
    while ((got = read(fd, reply, sizeof reply - 1)) > 0) {
        reply[got] = '\0';
        printf("el servidor contesta: %s", reply);
    }
    if (got < 0) {
        perror("read");
        exit(1);
    }
}

int main(int argc, char **argv) {
    if (argc < 4) {
        fprintf(stderr, "uso: %s <ip> <puerto> <bytes> [--chunk N] [--gap-ms N] [--nodelay] [--reply] [--abort]\n",
                argv[0]);
        return 2;
    }
    long long total = atoll(argv[3]);
    size_t chunk = BUF_SIZE;
    long gap_ms = 0;
    int nodelay = 0, want_reply = 0, abort_close = 0;
    for (int i = 4; i < argc; i++) {
        if (strcmp(argv[i], "--chunk") == 0 && i + 1 < argc) {
            chunk = (size_t)atol(argv[++i]);
        } else if (strcmp(argv[i], "--gap-ms") == 0 && i + 1 < argc) {
            gap_ms = atol(argv[++i]);
        } else if (strcmp(argv[i], "--nodelay") == 0) {
            nodelay = 1;
        } else if (strcmp(argv[i], "--reply") == 0) {
            want_reply = 1;
        } else if (strcmp(argv[i], "--abort") == 0) {
            abort_close = 1;
        } else {
            fprintf(stderr, "opción desconocida: %s\n", argv[i]);
            return 2;
        }
    }
    if (chunk == 0 || chunk > BUF_SIZE) {
        fprintf(stderr, "--chunk debe estar entre 1 y %d\n", BUF_SIZE);
        return 2;
    }

    struct sockaddr_in addr = {.sin_family = AF_INET, .sin_port = htons((uint16_t)atoi(argv[2]))};
    if (inet_pton(AF_INET, argv[1], &addr.sin_addr) != 1) {
        fprintf(stderr, "dirección inválida: %s\n", argv[1]);
        return 2;
    }
    int fd = socket(AF_INET, SOCK_STREAM, 0);
    if (fd < 0) {
        perror("socket");
        return 1;
    }
    if (nodelay) {
        int one = 1;
        if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &one, sizeof one) < 0) {
            perror("setsockopt TCP_NODELAY");
            return 1;
        }
    }
    if (connect(fd, (struct sockaddr *)&addr, sizeof addr) < 0) {
        perror("connect");
        return 1;
    }

    static char buf[BUF_SIZE];
    memset(buf, 'x', sizeof buf);
    long long sent = 0;
    while (sent < total) {
        size_t want = total - sent < (long long)chunk ? (size_t)(total - sent) : chunk;
        ssize_t done = write(fd, buf, want);
        if (done < 0) {
            if (errno == EINTR) {
                continue;
            }
            perror("write");
            return 1;
        }
        sent += done;
        if (gap_ms > 0 && sent < total) {
            pause_ms(gap_ms);
        }
    }
    if (want_reply) {
        if (shutdown(fd, SHUT_WR) < 0) {
            perror("shutdown");
            return 1;
        }
        read_reply(fd);
    }
    if (abort_close) {
        struct linger hard = {.l_onoff = 1, .l_linger = 0};
        if (setsockopt(fd, SOL_SOCKET, SO_LINGER, &hard, sizeof hard) < 0) {
            perror("setsockopt SO_LINGER");
            return 1;
        }
    }
    if (close(fd) < 0) {
        perror("close");
        return 1;
    }
    printf("enviados %lld bytes\n", sent);
    return 0;
}
