#!/usr/bin/env bash
set -eo pipefail

# Content of this script will be downloaded and executed on clients machine.
# for example "curl -SL http://install.vlayer.xyz | bash"

echo "Installing vlayerup..."

BASE_DIR="${XDG_CONFIG_HOME:-$HOME}"
VLAYER_DIR="${VLAYER_DIR-"${BASE_DIR}/.vlayer"}"
VLAYER_BIN_DIR="${VLAYER_DIR}/bin"
VLAYER_MAN_DIR="${VLAYER_DIR}/share/man/man1"

BIN_PATH="${VLAYER_BIN_DIR}/vlayerup"

# Temp URL, will be replaced with github url once the repo is public.
BIN_PATH="$VLAYER_BIN_DIR/vlayerup"
BIN_URL="https://install.vlayer.xyz/vlayerup"

# Create the .vlayer bin directory and vlayerup binary if it doesn't exist.
mkdir -p "${VLAYER_BIN_DIR}"
curl -sSf -L "${BIN_URL}" -o "${BIN_PATH}"
chmod +x "$BIN_PATH"

# Store the correct profile file (i.e. .profile for bash or .zshenv for ZSH).
case $SHELL in
*/zsh)
    PROFILE="${ZDOTDIR-"$BASE_DIR"}/.zshenv"
    PREF_SHELL=zsh
    ;;
*/bash)
    PROFILE=$BASE_DIR/.bashrc
    PREF_SHELL=bash
    ;;
*/fish)
    PROFILE=$BASE_DIR/.config/fish/config.fish
    PREF_SHELL=fish
    ;;
*/ash)
    PROFILE=$BASE_DIR/.profile
    PREF_SHELL=ash
    ;;
*)
    echo "vlayerup: could not detect shell, manually add ${VLAYER_BIN_DIR} to your PATH."
    exit 1
esac

# Only add vlayerup if it isn't already in PATH.
if [[ ":$PATH:" != *":${VLAYER_BIN_DIR}:"* ]]; then
    # Add the vlayerup directory to the path and ensure the old PATH variables remain.
    # If the shell is fish, echo fish_add_path instead of export.
    if [[ "$PREF_SHELL" == "fish" ]]; then
        echo >> "$PROFILE" && echo "fish_add_path -a $VLAYER_BIN_DIR" >> "$PROFILE"
    else
        echo >> "$PROFILE" && echo "export PATH=\"\$PATH:$VLAYER_BIN_DIR\"" >> "$PROFILE"
    fi
fi

echo
echo "Detected your preferred shell is $PREF_SHELL and added vlayerup to PATH."
echo "Run 'source $PROFILE' or start a new terminal session to use vlayerup."
echo "Then, simply run 'vlayerup' to install vlayer."
