#!/usr/bin/env bash

# Copyright © 2019-2021 Dynare Team
#
# This file is part of Dynare.
#
# Dynare is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Dynare is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Dynare.  If not, see <https://www.gnu.org/licenses/>.

set -ex

set -o errexit
readonly LOG_FILE="$2"/install.log
sudo touch "$LOG_FILE"
exec 1>"$LOG_FILE"
exec 2>&1

# Remove dummy payload
rm -f "$2"/dummy

# Test for Internet connection
if ! curl -s -m 4 https://github.com >/dev/null; then
    osascript -e 'display alert "Dynare Installation Error" message "Not able to connect to github.com. Either you are not connected to the internet or github.com is blocked where you are.\n\nAccess to GitHub is necessary to make Dynare work with the `use_dll` option on macOS.\n\nIf you cannot establish this connection or do not want to use the `use_dll` option of Dynare, please run the installer again and choose \"Customize\" from the \"Installation Type\" screen and uncheck the `GCC` option." as critical'
    echo "No internet connection to github.com"
    exit 1
fi

# Install Command Line Tools
# Checking that “xcode-select -print-path” returns a valid path is not enough, because
# the contents of that directory might have been removed (this is the official way of
# uninstalling CLT, see https://developer.apple.com/library/archive/technotes/tn2339/_index.html#//apple_ref/doc/uid/DTS40014588-CH1-HOW_CAN_I_UNINSTALL_THE_COMMAND_LINE_TOOLS_)
# Hence we also check that the directory contains the git binary.
if ! xcpath=$(/usr/bin/xcode-select -print-path) || [[ ! -x "$xcpath"/usr/bin/git ]]; then
    touch /tmp/.com.apple.dt.CommandLineTools.installondemand.in-progress
    SUC=$(softwareupdate -l |
              grep "\*.*Command Line" |
              grep -m1 "" |
              awk -F"*" '{print $2}' |
              sed -e 's/^ *//' |
              tr -d '\n')
    # On macOS 10.15 softwareupdate output is preceded by "Label: "
    [[ $SUC == Label:* ]] && SUC=${SUC#"Label: "}
    softwareupdate -i "$SUC" --verbose
    rm -f /tmp/.com.apple.dt.CommandLineTools.installondemand.in-progress
    softwareupdate -l
fi

# If CLT installation didn't work, exit
if ! xcpath=$(/usr/bin/xcode-select -print-path) || [[ ! -x "$xcpath"/usr/bin/git ]]; then
    osascript -e 'display alert "Dynare Installation Error" message "Not able to find Command Line Tools.\n\nCommand Line Tools is necessary to make Dynare work with the `use_dll` option on macOS.\n\nIf you cannot establish this connection or do not want to use the `use_dll` option of Dynare, please run the installer again and choose \"Customize\" from the \"Installation Type\" screen and uncheck the `GCC` option." as critical'
    echo "Command Line Tools not installed"
    exit 1
fi

# Ensure git is in the path
if ! which git >/dev/null; then
    osascript -e 'display alert "Dynare Installation Error" message "Not able to find Git even though the Command Line Tools have already been installed. This is likely a problem with your PATH environment variable.\n\nGit is necessary to make Dynare work with the `use_dll` option on macOS.\n\nIf you cannot establish this connection or do not want to use the `use_dll` option of Dynare, please run the installer again and choose \"Customize\" from the \"Installation Type\" screen and uncheck the `GCC` option." as critical'
    echo $PATH
    echo "Git not found in PATH"
    exit 1
fi

# Install Homebrew
BREWDIR="$2"/.brew
[ -d "$BREWDIR" ] || mkdir -p "$BREWDIR"

BREW_URL="https://github.com/Homebrew/brew"
BREW_BRANCH="master"

curl -\# -L "$BREW_URL"/tarball/"$BREW_BRANCH" | tar xz -m --strip 1 -C "$BREWDIR"

# Change ownership of Dynare directory
chown -R "$USER":staff "$2"

sudo -u "$USER" "$BREWDIR"/bin/brew tap homebrew/core
HOMEBREW_CACHE="$HOME"/Library/Caches/Homebrew-Dynare
HOMEBREW_NO_AUTO_UPDATE=1
[[ -z "${HOMEBREW_NO_ANALYTICS}" ]] && HOMEBREW_NO_ANALYTICS=1

# Move modified formulas to Homebrew Formula directory
mv "$2"/*.rb "$BREWDIR"/Library/Taps/homebrew/homebrew-core/Formula

# Install GCC & deps
sudo -u "$USER" "$BREWDIR"/bin/brew install gcc -v --force-bottle

exit 0
