#!/usr/bin/env python3

import os, sys, time
import subprocess

__version__ = "0.5"
usage = """
Usage: %(prog)s [-t n] command...

Executes command repeatedly until its output changes, then stops. Considers
both stdout and stderr.

Options:
  -t n           wait for n seconds between invocations. default is 1.0.

Version: %(version)s

Example: %(prog)s git pull
""" % {
    "prog": os.path.split(os.path.abspath(sys.argv[0]))[1],
    "version": __version__,
}

def main(cmd, seconds):
    (previous_stdout, previous_stderr) = (None, None)
    try:
        while True:
            process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            (stdout, stderr) = process.communicate()
            if (previous_stdout, previous_stderr) == (None, None):
                (previous_stdout, previous_stderr) = (stdout, stderr)
                sys.stderr.write(stderr.decode("utf8"))
                sys.stdout.write(stdout.decode("utf8"))
                continue
            if (previous_stdout, previous_stderr) == (stdout, stderr):
                time.sleep(seconds)
                sys.stdout.write(".")
                sys.stdout.flush()
                continue
            sys.stdout.write("\n")
            sys.stderr.write(stderr.decode("utf8"))
            sys.stdout.write(stdout.decode("utf8"))
            break
    except KeyboardInterrupt:
        sys.stdout.write("\n")
        sys.exit(1)

if __name__ == "__main__":
    seconds = 1
    args = sys.argv[1:]
    if len(args) >= 2 and args[0] == "-t":
        seconds = float(args[1])
        del args[:2]
    if len(args) >= 1:
        if args[0] == "--":
            # if your command actually begins with -, then prefix it with a -- arg.
            del args[0]
        elif args[0].startswith("-"):
            # such as --help or any other unrecognized command
            sys.exit(usage)
    if len(args) == 0:
        sys.exit(usage)
    cmd = args
    main(cmd, seconds)
