#!/usr/bin/env python

import os
import sys
from fabric.api import local, hide, settings
from fabric.colors import magenta, green
import beanstalk

command_name = os.path.split(os.path.splitext(__file__)[0])[-1]


def main():
    # get fab file
    beanstalk_install_path = os.path.split(os.path.split(beanstalk.__file__)[0])[0]
    beanstalk_package_path = os.path.join(beanstalk_install_path, 'beanstalk')
    fab_file_path = os.path.join(beanstalk_package_path, 'tasks/__init__.py')

    # Show usage
    if len(sys.argv) < 2:
        print magenta('Beanstalk-Stack man: {0}'.format(command_name), bold=True)
        print 'Hello, I\'m Jack who plant the beanstalk.'
        print 'Beanstalk-Stack version: {0}'.format(beanstalk.__version__)
        print ''
        print 'Usage: '
        print ''
        print '    {0} command1:argument1-1,argument1-2 [command2:argument2-1,argument2-2 ...]'.format(command_name)
        print '    {0} --list'.format(command_name)
        print ''
        with hide('running'):
            local('fab -f {0} --list'.format(fab_file_path))
        print ''
        print 'Beanstalk-Stack is built with ' + green('Python-Fabric') + '.'
        print 'So you can pass all arguments for fabric to {0}.'.format(command_name)
        print ''
        sys.exit(1)

    # Go!
    tasks = sys.argv[1:]
    with settings(hide('running', 'warnings', 'status'), warn_only=True):
        local('fab --linewise -f {fab_file} -u beanstalk --hide=status {tasks}'.format(
            fab_file=fab_file_path, tasks=' '.join(tasks)))


if __name__ == '__main__':
    main()
