#!/bin/bash

#==================================================
# Get the directory of the script file
#==================================================
# Using pwd alone will not work if you are not running the script from
# the directory it is contained in.
#
# $() acts as a kind of quoting for commands but they're run in their own context.
# dirname gives you the path portion of the provided argument (removing the file name).
#
# This command gets the script's source file pathname, strips it to just
# the path portion, cds to that path, then uses pwd to return the (effectively)
# full path of the script. This is assigned to the variable. After all of
# that, the context is unwound so you end up back in the directory you started
# at but with an environment variable containing the script's path.
dirScript="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

source $dirScript/util/util-spinner.sh
source $dirScript/brew-init.sh

#==================================================
# Make sure all the necessary tools are installed
#==================================================
function git-flow-init() {
    # Make sure git is installed
    echo "Making sure git is installed"
    brew install git > /dev/null 2>&1 & spinner $!
    brew upgrade git > /dev/null 2>&1 & spinner $!

    # Make sure git-flow-avh is installed
    echo "Installing/updating git-flow"
    brew uninstall git-flow > /dev/null 2>&1 & spinner $!
    brew install git-flow-avh > /dev/null 2>&1 & spinner $!
    brew upgrade git-flow-avh > /dev/null 2>&1 & spinner $!

    # Install bash-completion
    echo "Installing/updating bash completion for git-flow"
    brew install bash-completion > /dev/null 2>&1 & spinner $!

    # Add bash-completion shortcut to usr/local/etc
    if [ -f $(brew --prefix)/etc/bash_completion ]; then
    . $(brew --prefix)/etc/bash_completion & spinner $!
    fi

    # Add line to ~/.bash_profile, if it doesn't exist
    # echo '[ -f /usr/local/etc/bash_completion ] && . /usr/local/etc/bash_completion' >>~/.bash_profile & spinner $!

    # Copy git-flow-completion.bash to appropriate directory
    sudo cp $dirScript/resources/git-flow-completion.bash /usr/local/etc/bash_completion.d > /dev/null 2>&1 & spinner $!

    # Initialize git-flow-avh
    echo "Initializing git-flow"
    git add -A . && git commit --allow-empty -m "Initial commit" > /dev/null 2>&1 & spinner $!
    git flow init -fd > /dev/null 2>&1 & spinner $!

    # Checkout the develop branch and push to origin
    echo "Checking out develop branch and pushing to origin"
    git push origin master > /dev/null 2>&1 & spinner $!
    git checkout develop > /dev/null 2>&1 & spinner $!
    git push origin develop > /dev/null 2>&1 & spinner $!
}
