#!/bin/bash

# If Homebrew is installed:
echo "Checking if Homebrew is installed"
which -s brew
if [[ $? == 0 ]]; then

    echo "Homebrew is installed"
    # If OpenCV is installed:
    if [ -d "/usr/local/include/opencv2" ]; then
        echo "OpenCV is installed, checking for a new version..."
        if (brew outdated | grep opencv3 > /dev/null); then 
            echo "OpenCV is out-of-date, upgrading..." | log
            brew upgrade opencv3
        else
            echo "OpenCV is up-to-date"
        fi

    # If OpenCV is not intalled:
    else
        echo "OpenCV is not installed, installing..."
        brew install opencv3 --with-contrib --with-python3
        brew install pkg-config
    fi

# If Homebrew is not installed:
else
    echo "Homebrew is not installed - installing" | log
    # Install Homebrew
    ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
    brew update

    # Update ~/.bash_profile
    echo 'export PATH=/usr/local/bin:$PATH' >>~/.bash_profile
    source ~/.bash_profile

    # Install Python 2 and Python 3
    brew install python python3

    echo "Installing OpenCV" | log
    # Install OpenCV
    brew install opencv3 --with-contrib --with-python3

    # Install pkg-config (for easier compiling of OpenCV)
    brew install pkg-config
fi

echo "OpenCV installation complete!"
exit 0