#!/usr/bin/env python3

# Throttles the output of a command to a specified rate of seconds per line

import subprocess
import sys
import os
import fcntl
import time


def async_read_all(stream):
    fd = stream.fileno()
    fl = fcntl.fcntl(fd, fcntl.F_GETFL)
    fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK)
    try:
        return stream.read().decode("utf-8")
    except:
        return ""


class LineReader:
    def __init__(self, stream):
        self.stream = stream
        self.current_line = ""

    def read_last_full_line(self):
        text = async_read_all(self.stream)
        self.current_line += "" if text is None else text
        lines = self.current_line.split("\n")

        if len(lines) > 0:
            self.current_line = lines[-1]

        if len(lines) > 1:
            return lines[-2]
        else:
            return None


if __name__ == "__main__":
    if len(sys.argv) < 3:
        print(
            "Usage: python throttle_runner.py <throttle_rate_seconds> <command_to_run>"
        )
        sys.exit(1)

    throttle_rate = float(sys.argv[1])
    cmd = sys.argv[2:]

    process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

    stdout_reader = LineReader(process.stdout)
    stderr_reader = LineReader(process.stderr)

    while True:
        stdout_line = stdout_reader.read_last_full_line()
        stderr_line = stderr_reader.read_last_full_line()

        if stdout_line is not None:
            print(stdout_line)

        if stderr_line is not None:
            print(stderr_line)

        if process.poll() is not None:
            break

        if stdout_line is None and stderr_line is None:
            continue

        sys.stdout.flush()
        sys.stderr.flush()

        time.sleep(throttle_rate)
