#!/usr/bin/env python


'Launch inetd capable service on an ephemeral port'


import argparse
import contextlib
import socket
import subprocess
import sys


parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--host', default='127.0.0.1')
parser.add_argument('--port-file', required=True,
                    help='Report which port the service is bound to by '
                         'writing to this file.')
parser.add_argument('--loop', type=str, choices=('once', 'forever'),
                    default='once')
options, args = parser.parse_known_args()


ret = 0
with contextlib.closing(socket.socket()) as sock:
    sock.bind((options.host, 0))
    host, port = sock.getsockname()
    with open(options.port_file, 'w') as f:
        f.write('%s\n' % port)
    sock.listen(1)

    while True:
        conn, addr = sock.accept()
        with contextlib.closing(conn):
            ret = subprocess.call(args=args, stdin=conn, stdout=conn,
                                  stderr=conn, close_fds=True)

        if ret != 0:
            break
        if options.loop != 'forever':
            break

sys.exit(ret)
