#!/usr/bin/env bash

set -e

if [ -z "$SWIFTENV_ROOT" ]; then
  SWIFTENV_ROOT=$HOME/.swiftenv
fi
if [ ! -d "$SWIFTENV_ROOT" ]; then
  mkdir "$SWIFTENV_ROOT"
fi
export SWIFTENV_ROOT

find_source_path() {
  cd "$(dirname "${BASH_SOURCE[0]}")"
  cd "$(dirname "$(readlink "${BASH_SOURCE[0]}")")"
  echo "$PWD/.."
}

export SWIFTENV_SOURCE_PATH="$(find_source_path)"
export PATH="$SWIFTENV_SOURCE_PATH/libexec:$PATH"

usage() {
  echo "Usage: swiftenv [--version] <command>"
  echo
  echo "  version   Displays the current active Swift version"
  echo "  versions  Lists all installed Swift versions"
  echo "  global    Sets the global version of Swift"
  echo "  local     Sets the local application-specific version of Swift"
  echo "  install   Installs a version of Swift"
  echo "  uninstall Uninstalls a specific Swift version"
  echo "  rehash    Installs shims for Swift binaries"
  echo
  echo "Visit https://swiftenv.fuller.li for more info."
}

command="$1"
case "$command" in
"" )
  usage
  exit 1
  ;;
-v | --version )
  exec swiftenv---version
  ;;
-h | --help )
  usage
  ;;
* )
  command_path="$(command -v "swiftenv-$command" || true)"
  if ! [ -n "$command_path" ]; then
    echo "no such command \`$command'"
    exit 1
  fi

  shift 1
  exec "$command_path" "$@"
  ;;
esac
