#!/usr/bin/python

import logging
import optparse
import os
import subprocess
import sys

import blueprint.cli
from blueprint import context_managers

parser = optparse.OptionParser('Usage: %prog [-r] [-q] [<name>]')
parser.add_option('-r', '--relaxed',
                  dest='relaxed',
                  default=False,
                  action='store_true',
                  help='relax version constraints in generated code')
parser.add_option('-q', '--quiet',
                  dest='quiet',
                  default=False,
                  action='store_true',
                  help='operate quietly')
options, args = parser.parse_args()

if options.quiet:
    logging.root.setLevel(logging.CRITICAL)

if 1 < len(args):
    parser.print_usage()
    sys.exit(1)

b = blueprint.cli.read(options, args)

if 0 != os.geteuid():
    logging.warning('applying a blueprint may not work as a normal user')

with context_managers.mkdtemp():
    filename = b.sh(options.relaxed).dumpf()
    p = subprocess.Popen(['sh', filename], close_fds=True)
    p.communicate()
    sys.exit(p.returncode)
