#!/usr/bin/env python

# deploy - uses local repo like the charm store
#
# Copyright 2012 Canonical Ltd. All Rights Reserved
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import sys
import os
import os.path
import logging


logging.basicConfig(format='%(asctime)-15s %(name)s %(message)s', level=logging.INFO)
logger = logging.getLogger('juju-jitsu')

def main():
    charm_repo = os.environ.get("JUJU_REPOSITORY", None)
    if charm_repo is None:
        charm_repo = os.path.expanduser(os.environ.get("JUJU_JITSU_REPOSITORY", "~/charms"))
        os.setenv(JUJU_REPOSITORY=charm_repo)

    name = os.path.basename(sys.argv[0])

    if name == 'deploy':
        default_scheme = os.environ.get("JITSU_DEFAULT_SCHEME","cs")
        new_args = []
        found_charm = False
        for arg in sys.argv[1:]:
            if not found_charm and arg[0] != '-':
                found_charm = True
                if not ':' in arg:
                    if default_scheme is 'cs':
                        charm_repo = "charm store"
                    logger.info('deploying %s:%s from %s' % (default_scheme, arg, charm_repo))
                    arg = '%s:%s' % (default_scheme, arg)
            new_args.append(arg)
        sys.stderr.flush()
        os.execvp('juju', ['juju', 'deploy'] + new_args)
    elif name == 'upgrade-charm':
        os.execvp('juju', ['juju', 'upgrade-charm'] + sys.argv[1:])
    else:
        print >> sys.stderr, "Invalid subcommand name, running juju %s ..." % ([name]+sys.argv[1:])
        os.execvp('juju', ['juju', name] + sys.argv[1:])

if __name__ == '__main__':
    try:
        main()
    except Exception, e:
        logger.exception(e)
        sys.exit(1)
