#!/usr/bin/env bash
set -e

echo Installing aikup...

AIKEN_DIR=${AIKEN_DIR-"$HOME/.aiken"}
AIKEN_BIN_DIR="$AIKEN_DIR/bin"

BIN_URL="https://raw.githubusercontent.com/aiken-lang/aiken/main/aikup/aikup"
BIN_PATH="$AIKEN_BIN_DIR/aikup"

# Create the .aiken bin directory and aikup binary if it doesn't exist.
mkdir -p $AIKEN_BIN_DIR
curl -# -L $BIN_URL -o $BIN_PATH
chmod +x $BIN_PATH

# Store the correct profile file (i.e. .profile for bash or .zshrc for ZSH).
case $SHELL in
*/zsh)
    PROFILE=$HOME/.zshrc
    PREF_SHELL=zsh
    INJECT="export PATH=\"\$PATH:$AIKEN_BIN_DIR\""
    ;;
*/bash)
    PROFILE=$HOME/.bashrc
    PREF_SHELL=bash
    INJECT="export PATH=\"\$PATH:$AIKEN_BIN_DIR\""
    ;;
*/fish)
    PROFILE=$HOME/.config/fish/config.fish
    PREF_SHELL=fish
    INJECT="fish_add_path $AIKEN_BIN_DIR"
    ;;
*/ash)
    PROFILE=$HOME/.profile
    PREF_SHELL=ash
    INJECT="export PATH=\"\$PATH:$AIKEN_BIN_DIR\""
    ;;
*)
    echo "aikup: could not detect shell, manually add ${AIKEN_BIN_DIR} to your PATH."
    exit 1
esac

# Only add aikup if it isn't already in PATH.
if [[ ":$PATH:" != *":${AIKEN_BIN_DIR}:"* ]]; then
    # Add the aikup directory to the path and ensure the old PATH variables remain.
    echo >> $PROFILE && echo "$INJECT" >> $PROFILE
fi

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