#!/usr/bin/env python

"""
Usage:

  ./rtail.py user@host:path/foo.log bar.log host2:/path/baz.log
"""

import optparse
import os
import re
import select
import subprocess
import sys


def main():
    op = optparse.OptionParser()
    options, args = op.parse_args()
    streams = list()
    for arg in args:
        if re.match(r"^(.+@)?[a-zA-Z0-9.-]+:.+", arg):
            # this is a remote location
            hostname, path = arg.split(":", 1)
            s = subprocess.Popen(["ssh", hostname, "tail -f " + path], stdout=subprocess.PIPE)
            s.name = os.path.basename(arg)
            streams.append(s)
        else:
            s = subprocess.Popen(["tail", "-f", arg], stdout=subprocess.PIPE)
            s.name = os.path.basename(arg)
            streams.append(s)
    max_width = max((len(s.name) for s in streams))
    while True:
        r, _, _ = select.select(
            [stream.stdout.fileno() for stream in streams], [], [])
        for fileno in r:
            for stream in streams:
                if stream.stdout.fileno() != fileno:
                    continue
                data = os.read(fileno, 4096)
                if not data:
                    streams.remove(stream)
                    break
                for line in data.split('\n'):

                    line = "%s\n" % line.strip()
                    if line != "\n":
                        sys.stdout.write("%*s : " % (max_width, stream.name))
                        sys.stdout.write(line)
                break

if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        pass
