#!/bin/bash

# Only run in MacOS
if [ "$(uname)" == "Darwin" ]; then

    # Check for wget
    if ! [ -x "$(command -v wget)" ]; then
        echo 'Error: wget is not installed.' >&2
        exit 1
    fi

    # Check for Homebrew install
    if ! [ -x "$(command -v brew)" ]; then
        echo 'Error: brew is not installed.' >&2
        exit 1
    fi

    if ! [ -x "$(command -v montage)" ]; then
        # https://github.com/Homebrew/homebrew-core/blob/master/Formula/montage.rb
        # Necessary for combining the outputted level images into one output file
        echo 'Error: montage is not installed. Please install montage using "brew install montage"' >&2
        exit 1
    fi

    # Try to make a create the folder structure if it doesn't exist
    mkdir -p bin/darwin

    # Fetch latest zip file of CMFT for MacOS and unzip in the correct folder
    wget -qO- https://github.com/timvanscherpenzeel/cmft-bin/raw/master/cmft_osx64.zip | bsdtar -xvf- -C ./bin/darwin

    # Extract binary from the zip file
    mv ./bin/darwin/cmft_osx64/cmft ./bin/darwin/

    # Clean up included .tga file and example bash script included in the zip file
    rm -rf ./bin/darwin/cmft_osx64

    # Remove folder that only holds .ds_store file
    rm -rf ./bin/darwin/__MACOSX

    # Alternatively build from source
    # git clone https://github.com/TimvanScherpenzeel/cmft ./bin/darwin/cmft-lib
    # cd ./bin/darwin/cmft-lib
    # make
    # make osx-release64
    # mv _build/osx64_clang/bin/cmftRelease ../
    # cd ../
    # rm -rf cmft-lib
    # mv cmftRelease cmft

    # Download HDR2PNG and compile for MacOS
    git clone https://github.com/plepers/hdr2png ./bin/darwin/hdr2png-lib
    cd ./bin/darwin/hdr2png-lib
    git submodule init
    git submodule update

    # Compile
    mkdir _build
    cd _build
    cmake ../
    make

    # Move to bin folder and remove
    mv hdr2png ../../
    cd ../../
    rm -rf hdr2png-lib
else
    echo 'Error: currently only the auto setup works on MacOS.' >&2
    exit 1
fi
