#!/usr/bin/env python
import sys
import re
import os


# Messages
NO_ORDER = "No order given. Type 'cook -l' for a list of orders\n"
VERSION = 'LittleChef {0}'
INSTALL_ERROR = "LittleChef was not correctly installed: "\
              "Couldn't import littlechef.py"

## Try to import package and set the fabfile path ##
file_path = None
try:
    import littlechef # Needed later for version
    # Get fabfile full path
    from littlechef import runner # Checks that we are able to import module
    file_path = re.sub(r'\.pyc$', '.py', runner.__file__)
except ImportError:
    print(INSTALL_ERROR)
    sys.exit(1)

## Process args list and call fabric main() ##
if not sys.argv:
    print(NO_ORDER)
else:
    if (os.path.basename(sys.argv[0]).startswith('cook')):
        # In windows, the first argument may be just "cook"
        cook_cmd = sys.argv[0]
    else:
        cook_cmd = None
    if len(sys.argv) == 1 and cook_cmd:
        # All that is in sys.argv is the cook command.
        print(NO_ORDER)
    else:
        # Check for version, that overrides everything else.
        for arg in '-v', '-V', '--version':
            if arg in sys.argv: 
                print(VERSION.format(littlechef.version))
                sys.exit(0)
        # Otherwise, insert our fabfile at the correct place
        if cook_cmd:
            sys.argv[1:1] = ['-f', file_path]
        else:
            sys.argv[0:0] = ['-f', file_path]
        # Pass control over to fabric
        # Fabric should now import runner with COOKING = True
        littlechef.COOKING = True
        import fabric.main
        fabric.main.main()
