/* amosfeed.c -- AM·OS pipe feeder with byte-accurate progress.
* Copyright 2026 ANNE Media - https://anne.media
* All rights reserved.
*
* Redistribution and use of this script, with or without modification, is
* permitted provided that the following conditions are met:
*
* 1. Redistributions of this script must retain the above copyright
*    notice, this list of conditions and the following disclaimer.
*
*  THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
*  WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
*  MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO
*  EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
*  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
*  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
*  OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
*  WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
*  OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
*  ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Reads stdin, writes stdout verbatim, and periodically publishes a
* status line to a file so the installer can render an accurate
* import progress bar.
*
* Status file format (single line, atomic via write+rename):
*     <bytes_done> <bytes_total> <elapsed_ms>\n
*
* Build (see Makefile). The ISO build should place the resulting
* binary at payload/annode/amosfeed next to this source.
*/

#define _POSIX_C_SOURCE 200809L

#include <errno.h>
#include <fcntl.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>

#define CHUNK_BYTES (1 << 20)   /* 1 MiB read size */

static volatile sig_atomic_t g_stop = 0;
static void on_signal(int sig) { (void)sig; g_stop = 1; }

static long long monotonic_ms(void) {
    struct timespec ts;
    if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0) return 0;
    return (long long)ts.tv_sec * 1000LL + ts.tv_nsec / 1000000LL;
}

static int write_status(const char *path,
                        long long done,
                        long long total,
                        long long elapsed_ms)
{
    char tmp[600];
    int n = snprintf(tmp, sizeof tmp, "%s.tmp", path);
    if (n < 0 || n >= (int)sizeof tmp) return -1;

    int fd = open(tmp, O_WRONLY | O_CREAT | O_TRUNC, 0644);
    if (fd < 0) return -1;

    char line[128];
    int len = snprintf(line, sizeof line, "%lld %lld %lld\n",
                       done, total, elapsed_ms);
    if (len < 0 || len >= (int)sizeof line) { close(fd); unlink(tmp); return -1; }

    ssize_t w = write(fd, line, (size_t)len);
    if (w != (ssize_t)len) { close(fd); unlink(tmp); return -1; }
    if (close(fd) != 0)    { unlink(tmp); return -1; }

    return rename(tmp, path);
}

static void usage(void) {
    fprintf(stderr,
        "usage: amosfeed --status PATH [--total BYTES] [--interval MS]\n");
}

int main(int argc, char **argv)
{
    long long total = 0;
    long long interval_ms = 500;
    const char *status = NULL;

    for (int i = 1; i < argc; i++) {
        if      (!strcmp(argv[i], "--total")    && i + 1 < argc) total       = atoll(argv[++i]);
        else if (!strcmp(argv[i], "--status")   && i + 1 < argc) status      = argv[++i];
        else if (!strcmp(argv[i], "--interval") && i + 1 < argc) interval_ms = atoll(argv[++i]);
        else { usage(); return 2; }
    }
    if (!status) { usage(); return 2; }
    if (interval_ms < 100) interval_ms = 100;

    struct sigaction sa;
    memset(&sa, 0, sizeof sa);
    sa.sa_handler = on_signal;
    sigaction(SIGTERM, &sa, NULL);
    sigaction(SIGINT,  &sa, NULL);
    signal(SIGPIPE, SIG_IGN);

    static char buf[CHUNK_BYTES];
    long long done = 0;
    long long t0   = monotonic_ms();
    long long last = t0;

    write_status(status, 0, total, 0);

    for (;;) {
        ssize_t r = read(STDIN_FILENO, buf, sizeof buf);
        if (r < 0) {
            if (errno == EINTR) { if (g_stop) break; continue; }
            perror("amosfeed: read");
            return 1;
        }
        if (r == 0) break;   /* EOF */

        ssize_t off = 0;
        while (off < r) {
            ssize_t w = write(STDOUT_FILENO, buf + off, (size_t)(r - off));
            if (w < 0) {
                if (errno == EINTR) continue;
                perror("amosfeed: write");
                return 1;
            }
            off += w;
        }
        done += r;

        long long now = monotonic_ms();
        if (now - last >= interval_ms) {
            write_status(status, done, total, now - t0);
            last = now;
        }
        if (g_stop) break;
    }

    write_status(status, done, total, monotonic_ms() - t0);
    return 0;
}