"""Install packages via the MacOSX Homebrew and Linux Linuxbrew package manager.
https://github.com/mxcl/homebrew
https://github.com/Homebrew/linuxbrew
"""
from __future__ import print_function
import contextlib
from distutils.version import LooseVersion
import os
import sys

import yaml

from cloudbio.custom import system, shared
from cloudbio.flavor.config import get_config_file
from cloudbio.fabutils import quiet, find_cmd
from cloudbio.package import cpan
from cloudbio.package.shared import _yaml_to_packages

from fabric.api import cd, settings

BOTTLE_URL = "https://s3.amazonaws.com/cloudbiolinux/brew_bottles/{pkg}-{version}.x86_64-linux.bottle.tar.gz"
BOTTLE_SUPPORTED = set(["isaac-aligner", "isaac-variant-caller", "cmake"])

def install_packages(env, to_install=None, packages=None):
    """Install packages using the home brew package manager.

    Handles upgrading brew, tapping required repositories and installing or upgrading
    packages as appropriate.

    `to_install` is a CloudBioLinux compatible set of top level items to add,
    alternatively `packages` is a list of raw package names.
    """
    config_file = get_config_file(env, "packages-homebrew.yaml")
    if to_install:
        (packages, _) = _yaml_to_packages(config_file.base, to_install, config_file.dist)
    # if we have no packages to install, do not try to install or update brew
    if len(packages) == 0: