"""
port-for is a command-line utility that
helps with local TCP ports managment. It
finds 'good' unused TCP localhost port and
remembers the association.

Usage:
    port-for <NAME>
    port-for --bind <NAME>
    port-for --bind <NAME> --port <NUMBER>
    port-for <NAME> --port <NUMBER>
    port-for --unbind <NAME>
    port-for --list
    port-for --version
    port-for --help

Options:
  -h --help             Show this screen.
  -v, --version         Show version.
  -b FOO, --bind FOO    Find and return a port for FOO; this is an alias for
                        'port-for FOO'.
  -p PORT, --port PORT  (Optional) specific port number for the --bind command.
  -u FOO, --unbind FOO  Remove association for FOO.
  -l, --list            List all associated ports.
"""

import sys
import port_for
from port_for.docopt import docopt

store = port_for.PortStore()

def _list():
    for app, port in store.bound_ports():
        sys.stdout.write("%s: %s\n" % (app, port))

def _bind(app, port=None):
    port = store.bind_port(app, port)
    sys.stdout.write("%s\n" % port)

def _unbind(app):
    store.unbind_port(app)

if __name__ == '__main__':
    args = docopt(__doc__, version='port-for %s' % port_for.__version__)
    if args['<NAME>']:
        _bind(args['<NAME>'], args['--port'])
    elif args['--bind']:
        _bind(args['--bind'], args['--port'])
    elif args['--list']:
        _list()
    elif args['--unbind']:
        _unbind(args['--unbind'])
