#!/usr/bin/env bash

PROJ128_DIR="$(readlink -f "${PROJ128_DIR:-$HOME/.proj128}")"

if [ -d "$PROJ128_DIR" ]
then
    rm -dfr "$PROJ128_DIR"
fi

if which git &> /dev/null
then
    git clone https://github.com/stefanwimmer128/proj128.git "$PROJ128_DIR"
    cd "$PROJ128_DIR"
    tag="$(git describe --tags $(git rev-list --tags --max-count=1))"
    git checkout tags/$tag &> /dev/null
else
    echo "Git required for installation!"
    exit 1
fi

if ! which wget &> /dev/null
then
    echo "Installing jq..."
    
    wget -O "$PROJ128_DIR/bin/jq" "https://github.com/stedolan/jq/releases/download/$(curl -s https://api.github.com/repos/stedolan/jq/releases/latest | grep "tag_name" | cut -d\" -f4)/jq-linux64"
    chmod a+x "$PROJ128_DIR/bin/jq"
else
    echo "WGet required for installation!"
fi

if [[ "$PROJ128_DIR" == "$HOME"* ]]
then
    PROJ128_DIR="\$HOME${PROJ128_DIR#$HOME}"
fi

if ! which proj128 &> /dev/null
then
    cat >> "$HOME/.bashrc" << eof

export PROJ128_DIR="${PROJ128_DIR//$HOME/\$HOME}"
export PATH="\$PROJ128_DIR/bin:\$PATH"
eof
fi

echo "proj128 $tag installed!"
