#!/usr/bin/env python
import time
import os
import sys
import json

from psprofile.main import main


if __name__ == '__main__':
    import argparse

    parser = argparse.ArgumentParser(description='Profile resource usage of a command')
    parser.add_argument('-o', '--output_file', help='File to store output of profile to.')
    parser.add_argument('-i', '--poll_interval', type=int, default=1,
                        help='How often to poll the resource usage information in /proc, in seconds (default 1).')
    # parser.add_argument('command', nargs=argparse.REMAINDER, help="The command to run.")
    parser.add_argument('command_script', help="path to a shell script to run")
    parser.add_argument('-w', '--wait_for_command_script', help="time to wait for command_script to exist"
                                                                "(useful to handle eventual consistency on shared filesystems)", default=0)
    args = parser.parse_args()

    start = time.time()
    while not os.path.exists(args.command_script):
        if time.time() - start > args.wait_for_command_script:
            raise IOError('command_script `%s` does not exist!' % args.command_script)
        time.sleep(.5)

    # Run Profile
    output = main(args.command_script, args.poll_interval)

    # Write output
    output_json = json.dumps(output, indent=4)

    if args.output_file:
        if os.path.exists(args.output_file):
            os.unlink(args.output_file)
        with open(args.output_file, 'w') as fh:
            fh.write(output_json)
    else:
        print >> sys.stdout, output_json

    sys.exit(output['exit_status'])