#!/bin/bash
set -e

PACKAGE=$1
INSTALL_DESTINATION=$2

function IsBrewPkgInstalled
{
    # Check if Homebrew is installed
    /usr/bin/which brew > /dev/null
    if [ $? -eq 0 ]
    then
        # Check if the package has been installed
        brew ls --versions "$1" > /dev/null
        if [ $? -eq 0 ]
        then
            return 0
        fi
    fi
    return 1
}

# Check if Java GCM is present on this system and unlink it should it exist
if [ -L /usr/local/bin/git-credential-manager ] && IsBrewPkgInstalled "git-credential-manager";
then
    brew unlink git-credential-manager
fi

# Create symlink to GCM in /usr/local/bin
mkdir -p /usr/local/bin
/bin/ln -Fs "$INSTALL_DESTINATION/git-credential-manager" /usr/local/bin/git-credential-manager

# Configure GCM for the current user (running as the current user to avoid root
# from taking ownership of ~/.gitconfig)
sudo -u ${USER} "$INSTALL_DESTINATION/git-credential-manager" configure

exit 0
