Shell autocompletion support.

def autocomplete(force=False):
    " Shell autocompletion support. "

    if 'MAKESITE_AUTO_COMPLETE' not in environ and not force:
        return

    commands = filter(lambda cmd: cmd != 'main', ACTIONS.keys())

    cwords = environ['COMP_WORDS'].split()[1:]
    cword = int(environ['COMP_CWORD'])

    try:
        current = cwords[cword - 1]
    except IndexError:
        current = ''

    try:
        sub_action = [cmd for cmd in commands if cmd in cwords][0]
        if sub_action in ['info', 'uninstall', 'update', 'template']:
            if settings.MAKESITE_HOME:
                if not current or current.startswith('/'):
                    sites = list(gen_sites(settings.MAKESITE_HOME))
                    print ' '.join(site.deploy_dir for site in sites if site.
                                   deploy_dir.startswith(current))
                else:
                    names = map(lambda s: s.get_name(
                    ), gen_sites(settings.MAKESITE_HOME))
                    print ' '.join(
                        name for name in names if name.startswith(current))
        elif sub_action == 'install' and (cwords[-1] == '-m' or (current and cwords[-2] == '-m')):
            print ' '.join(
                mod for mod in get_base_modules() if mod.startswith(current))
        elif sub_action == 'install' and (cwords[-1] == '-t' or (current and cwords[-2] == '-t')):
            print ' '.join(tpl for tpl in get_base_templates(
            ) if tpl.startswith(current))
        elif sub_action == 'module':
            print ' '.join(
                tpl for tpl in get_base_modules() if tpl.startswith(current))
    except IndexError:
        print (' '.join(a for a in commands if a.startswith(current)))
    sys.exit(1)