#!/usr/bin/env python
import repeat_cli.repeat
import sys
import argparse


def main():
    arg_parser = argparse.ArgumentParser(description="Repeats a given command until specified conditions are met")
    arg_parser.add_argument('-c', '--count', type=int, default=0,
                            help='Runs the downstream command at most this many times. "0" for infinite. Default: 0.')
    arg_parser.add_argument('-q', '--quit-on-zero', action='store_true',
                            help='Stops repeating when the given command exits 0')
    arg_parser.add_argument('-b', '--beep-on-zero', action='store_true',
                            help='Beeps when the given command exits 0')
    arg_parser.add_argument('-Q', '--quit-on-nonzero', action='store_true',
                            help='Stops repeating when the given command exits non-zero')
    arg_parser.add_argument('-B', '--beep-on-nonzero', action='store_true',
                            help='Beeps when the given command exits non-zero')
    arg_parser.add_argument('-0', '--always-exit-zero', action='store_true',
                            help='By default ' + sys.argv[0] +
                                 ' will exit with the exit code of the downstream process. ' +
                                 'Override that behavior to always exit 0.')
    arg_parser.add_argument('-n', '--interval', type=int, default=1,
                            help='The time in seconds between each attempt. Default: 1.')
    arg_parser.add_argument('-p', '--print-exit-code', action='store_true',
                            help='Print the exit code after each attempt')
    arg_parser.add_argument('-s', '--silent', action='store_true',
                            help='Suppress output from downstream process')
    arg_parser.add_argument('command', nargs=argparse.REMAINDER, help="The command to run.")

    result = arg_parser.parse_args()
    exit_code = repeat_cli.repeat.execute(**result.__dict__)
    sys.exit(exit_code)


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