#!/usr/bin/python

import errno
import logging
import optparse
import re
import subprocess
import sys

import blueprint
from blueprint import context_managers
from blueprint import git

parser = optparse.OptionParser(
    'Usage: %prog [-m <message>] [-q] <minuend> <subtrahend> <difference>')
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 3 != len(args):
    parser.print_usage()
    sys.exit(1)
minuend, subtrahend, difference = args

try:
    b_m = blueprint.Blueprint(name=minuend)
except blueprint.NotFoundError:
    logging.error('blueprint {0} does not exist'.format(minuend))
    sys.exit(1)
except blueprint.NameError:
    logging.error('invalid blueprint name {0}'.format(minuend))
    sys.exit(1)
try:
    b_s = blueprint.Blueprint(name=subtrahend)
except blueprint.NotFoundError:
    logging.error('blueprint {0} does not exist'.format(subtrahend))
    sys.exit(1)
except blueprint.NameError:
    logging.error('invalid blueprint name {0}'.format(subtrahend))
    sys.exit(1)

with context_managers.mkdtemp():
    b_d = b_m - b_s
    try:
        b_d.name = difference
    except blueprint.NameError:
        logging.error('invalid blueprint name {0}'.format(difference))
        sys.exit(1)

    # Grab all of the source tarballs from the minuend.
    # TODO Factor this pattern into a method on `blueprint.Blueprint`s.
    tree = git.tree(getattr(b_m, '_commit'))
    for dirname, filename in sorted(b_m.sources.iteritems()):
        blob = git.blob(tree, filename)
        content = git.content(blob)
        f = open(filename, 'w')
        f.write(content)
        f.close()

    b_d.commit(options.message or '')
