#!/bin/sh

DOTS=$(dirname "$0")/..
cd "$DOTS" || (echo "Directory not found: $DOTS"; exit 1)
DOTS="$PWD"

install_xcode() {
    if [ "$(uname)" = "Darwin" ]
    then
        if ! (xcode-select --version > /dev/null 2>&1)
        then
            xcode-select --install
        fi
        echo "xcode ✓"
    fi
}

install_homebrew() {
    if ! (which /usr/local/bin/brew > /dev/null)
    then
        printf "homebrew ✕\n\n"
        printf "\ninstalling homebrew..."
        /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)"
        echo ""
    fi

    echo "homebrew ✓"
}

install_brews() {
    brewfile=$DOTS/homebrew/core.Brewfile
    if ! (/usr/local/bin/brew bundle check --file "$brewfile" > /dev/null)
    then
        /usr/local/bin/brew bundle --file "$brewfile"
    fi

    echo "brews installed ✓"
}

use_fish_shell() {
    if ! (which fish > /dev/null)
    then
        echo "Install fish before continuing"
        echo "You can do: brew install fish"
        echo "Or add fish to homebrew/Brewfile and rerun"
        exit 1
    fi
    FISH_SHELL=$(which fish)
    if ! (grep "$FISH_SHELL" /etc/shells > /dev/null)
    then
        echo "Modifying /etc/shells"
        echo "Requires sudo password"
        echo "$FISH_SHELL" | sudo tee -a /etc/shells
    fi
    if ! (echo "$SHELL" | grep fish > /dev/null)
    then
        echo "Changing default shell to fish"
        echo "Requires sudo password"
        sudo chsh -s "$FISH_SHELL"
    fi

    echo "fish ✓"
}

printf "\nbootstrapping...\n\n"
install_xcode
install_homebrew
install_brews
use_fish_shell
("$DOTS/scripts/setup_symlinks")

echo ""
echo "consider running other scripts:"
echo " - brews"
echo " - casks"
echo " - configure_macos"
echo " - rust"
echo " - cargos"
echo ""