#!/usr/bin/env python
import glob
import subprocess
import shutil
import re
import yaml
import sys
import os
import argparse


def main(package, version='default', image=None, dryrun=False, clone=False, quiet=False):
    parent_dir = os.path.dirname(os.path.abspath(__file__))
    build_dir = os.path.join(parent_dir, package, version)
    log_file = os.path.join(parent_dir, package, 'build.log')

    _store_new_version = False
    if not os.path.exists(build_dir):
        if os.path.exists(os.path.join(parent_dir, package, 'default')):
            build_dir = os.path.join(parent_dir, package, 'default')
            # In this case it's an "unknown" version, so we'll just be friendly
            # and serialize their yaml into a new versioned directory for them.
            _store_new_version = True
        else:
            if version == 'default':
                print "Default recipe for %s not found" % image
            else:
                print "Neither a default recipe, nor a recipe at version %s were found" % version
            sys.exit(4)

    if _store_new_version and clone:
        target = os.path.join(parent_dir, package, version)
        # Clone the default
        shutil.copytree(build_dir, target)
        # Update other variables.
        build_dir = target

    tentative_yaml_paths = glob.glob(os.path.join(build_dir, 'build*.yml'))
    if not tentative_yaml_paths:
        print "No build yaml files found at %s/build*.yml" % build_dir
        sys.exit(3)

    if not dryrun: