#!/usr/bin/env python
"""
Buffer the incoming lines, preventing them from being output too fast.
In other words, insert a minimal delay between each incoming line.

For example::

  cat server.log | rubbercat -r -t.200

"""
__author__ = 'Martin Blais <blais@furius.ca>'

import sys
from time import time, sleep
from random import random


def write(s):
    sys.stdout.write(s)
    sys.stdout.flush()

def main():
    import optparse
    parser = optparse.OptionParser(__doc__.strip())

    parser.add_option('-i', '--let-lines', '--init-lines', action='store', type='int',
                      default=0,
                      help="Specify the number of lines that we should immediately "
                      "let through on startup (default: 0).")

    parser.add_option('-t', '--delay', action='store', type='float',
                      default=100,
                      help="Minimal time delay, in milliseconds (default is 100ms).")

    parser.add_option('-r', '--randomize', '--random', action='store_true',
                      help="Randomize the time delay.  "
                      "The delay becomes a maximum in this is turned on.")

    opts, args = parser.parse_args()

    secs = min_secs = opts.delay/1000.

    read = sys.stdin.readline

    # Let the initial lines through.
    n = opts.let_lines
    while n > 0:
        line = read()
        if not line:
            break
        write(line)
        n -= 1

    last_t = time()
    while 1:
        line = read()
        if not line:
            break

        t = time()
        if t < last_t + secs:
            sleep(last_t + secs - t)

        last_t = time()
        write(line)

        if opts.randomize:
            # Reinitialize the random min secs delay.
            secs = random() * opts.delay

if __name__ == '__main__':
    try:
        main()
    except IOError, e: # Broken pipe
        pass
