#!/usr/bin/env bash
##makedesc: Install git (latest)

set -eo pipefail

installed() { command -v "$1" >/dev/null 2>&1; }

require() {
    local missing=()
    for pkg in "$@"; do
        installed "$pkg" || missing+=("$pkg")
    done
    if [ ${#missing[@]} -gt 0 ]; then
        if [ "$(uname -s)" = "Darwin" ]; then
            if installed brew; then
                brew install "${missing[@]}"
            else
                echo "ERROR: Missing: ${missing[*]}. Install manually or use brew." >&2
                exit 1
            fi
        else
            sudo apt install -y "${missing[@]}"
        fi
    fi
}

download() {
    if installed wget; then
        wget -q --show-progress "$1" -O "$2"
    else
        curl -fsSL "$1" -o "$2"
    fi
}

clone_quick() {
    git clone --depth=1 --single-branch "$@"
}

install() {
    echo
    echo "==============================================="
    echo "Installing git"
    echo "==============================================="
    echo

    require make

    if installed git; then
        if [ -d "$HOME/install/git" ]; then
            cd "$HOME/install/git"
            git pull
        else
            clone_quick "https://github.com/git/git.git" "$HOME/install/git"
            cd "$HOME/install/git"
        fi
        sudo make prefix=/usr/local all
        sudo make prefix=/usr/local install
    else
        require wget unzip
        mkdir -p "$HOME/install/git"
        download "https://github.com/git/git/archive/master.zip" "/tmp/git.zip"
        unzip -oq "/tmp/git.zip" -d "$HOME/install/git"
        rm /tmp/git.zip
        cd "$HOME/install/git/git-master"
        sudo make prefix=/usr/local all
        sudo make prefix=/usr/local install
        cd -
        rm -rf git
        clone_quick "https://github.com/git/git.git" "$HOME/install/git"
    fi

    echo
    echo "Finish!"
    git --version
    echo
}

case "$1" in
    *) install ;;
esac
