#!/usr/bin/python

import logging
import optparse
import readline
import sys

import blueprint
from blueprint import cli
from blueprint import context_managers
from blueprint import interactive

parser = optparse.OptionParser('Usage: %prog [-m <message>] [-q] <src> <dest>')
parser.add_option('-m', '--message',
                  dest='message',
                  default=None,
                  help='commit message')
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 len(args) not in (1, 2):
    parser.print_usage()
    sys.exit(1)

b_s = blueprint.cli.read(options, args)
try:
    b_d = blueprint.Blueprint(args[-1])
except blueprint.NameError:
    logging.error('invalid blueprint name {0}'.format(args[-1]))
    sys.exit(1)

def choose():
    """
    Return the destination blueprint object or `None`.
    """
    prompt = 'Include in blueprint {0}? [y/n] '.format(args[-1])
    yn = raw_input(prompt).lower()
    while yn not in ('y', 'n', 'yes', 'no'):
        yn = raw_input(prompt)
    return b_d if 'y' == yn[0] else None

try:
    with context_managers.mkdtemp():
        interactive.walk(b_s, choose)
        b_d.commit(options.message or '')
except IOError:
    pass
except KeyboardInterrupt:
    print('') # Expect this kind of thing in an interactive process.
