#!/usr/bin/env python
from __future__ import print_function
import sys
import os


# Messages
NO_ORDER = "No order given. Type 'fix -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 ##
fabfile = None
try:
    import littlechef
    # Get absolute directory for imported littlechef package
    dirname = os.path.dirname(os.path.abspath(littlechef.__file__))
    # Build path to the runner fabfile to pass to fabric
    fabfile = os.path.join(dirname, 'runner.py')
except ImportError:
    print(INSTALL_ERROR)
    sys.exit(1)

## Process args list and call fabric's main() ##
if not sys.argv:
    print(NO_ORDER)
else:
    if (os.path.basename(sys.argv[0]).startswith('fix')):
        # In windows, the first argument may be just "fix"
        fix_cmd = sys.argv[0]
    else:
        fix_cmd = None
    if len(sys.argv) == 1 and fix_cmd:
        # All that is in sys.argv is the fix 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)
        for arg in sys.argv:
            if "env:" in arg:
                chef_environment = arg.split(":")[1]
                if chef_environment == '':
                    print("Error: No environment was given", file=sys.stderr)
                    sys.exit(1)
                else:
                    littlechef.chef_environment = chef_environment
                sys.argv.remove(arg)
        # Otherwise, insert our fabfile at the correct place
        if fix_cmd:
            sys.argv[1:1] = ['-f', fabfile]
        else:
            sys.argv[0:0] = ['-f', fabfile]
        # Pass control over to fabric
        # Fabric should now import runner with COOKING = True
        littlechef.__cooking__ = True
        from fabric import main
        main.main()
