#!/usr/bin/env bash
# @file SDKMAN Install
# @brief Ensures SDKMAN is installed.
# @description
#     This script ensures SDKMAN (a Java version manager) is installed using the method recommended on [their
#     website](https://sdkman.io/).

{{ includeTemplate "universal/profile" }}
{{ includeTemplate "universal/logg" }}

### Re-source ~/.bashrc
if [ -z "$SDKMAN_DIR" ]; then
  logg info 'SDKMAN_DIR is undefined so ~/.bashrc is being re-sourced' && source ~/.bashrc
fi

### SDKMan ~/.bashrc settings
if command -v brew > /dev/null && command -v sdkman-cli > /dev/null; then
  export SDKMAN_DIR="$(brew --prefix sdkman-cli)/libexec"
  . "$SDKMAN_DIR/bin/sdkman-init.sh"
elif [ -d "${XDG_DATA_HOME:-$HOME/.local/share}/sdkman" ]; then
  export SDKMAN_DIR="${XDG_DATA_HOME:-$HOME/.local/share}/sdkman"
  . "$SDKMAN_DIR/bin/sdkman-init.sh"
else
  logg logg 'Unable to find SDKMAN instance'
fi

### Ensure SDKMan is installed (https://sdkman.io/)
if [ ! -d "$SDKMAN_DIR" ]; then
  logg info 'Installing SDKMan via curl -s https://get.sdkman.io?rcupdate=false'
  logg info "Install directory: $SDKMAN_DIR"
  curl -s "https://get.sdkman.io?rcupdate=false" | bash
  if [ -f "$SDKMAN_DIR/bin/sdkman-init.sh" ]; then
    . "$SDKMAN_DIR/bin/sdkman-init.sh"
    logg info 'Running sdk install java' && sdk install java
  else
    logg warn 'SDKMAN_DIR/bin/sdkman-init.sh is missing'
  fi
else
  logg info 'SDKMan appears to already be installed.'
  logg info 'Running sdk update'
  if command -v sdk > /dev/null; then
    sdk update
  else
    logg warn 'Unable to run sdk update because the sdk command is unavailable'
  fi
fi
