#!/bin/bash
set -e
set -x

mkdir -p $MAILPILE_BREW_ROOT
cd "$MAILPILE_BREW_ROOT"

if [ "$KEEP_BUNDLE" = "" -a "$SKIP_HOMEBREW" = "" ]; then

    # Install Mailpile Dependencies from homebrew.
    #
    [ -e "$BUILD_DIR/Homebrew.git"  ] && mv "$BUILD_DIR/Homebrew.git" .git || true
    [ -e "$BUILD_DIR/Homebrew.lib"  ] && mv "$BUILD_DIR/Homebrew.lib" Library/Homebrew || true
    [ -e "$BUILD_DIR/Homebrew.taps" ] && mv "$BUILD_DIR/Homebrew.taps" Library/Taps || true

    [ -e bin/brew ] || \
        curl -kL https://github.com/Homebrew/brew/tarball/master \
        | tar xz --strip 1
    echo
    brew update
    brew install openssl@$OPENSSL_VERSION \
        || brew upgrade openssl@$OPENSSL_VERSION
    brew link --force openssl@$OPENSSL_VERSION
    brew install "$SYMLINKS_SRC"
    for p in \
        libjpeg \
        gnupg@$GNUPG_VERSION \
        python@$PYTHON_MAJOR_VERSION \
        tor \
    ; do
        brew install "$p" || brew upgrade "$p"
    done
fi

[ -e .git ]             && mv .git             "$BUILD_DIR/Homebrew.git"  || true
[ -e Library/Homebrew ] && mv Library/Homebrew "$BUILD_DIR/Homebrew.lib"  || true
[ -e Library/Taps ]     && mv Library/Taps     "$BUILD_DIR/Homebrew.taps" || true
