#!/bin/bash

set -e

OS="$(uname -s)"
INSTALL_DIR="$HOME/.flashlight/bin"
CURRENT_SHELL="$(basename "$SHELL")"

set_filename() {
  case "$OS" in
    "Linux") FILENAME="flashlight-linux" ;;
    "Darwin") FILENAME="flashlight-macos" ;;
    CYGWIN*) FILENAME="flashlight-win.exe" ;;
    MINGW*) FILENAME="flashlight-win.exe" ;;
    *) echo "OS $OS is not supported."
       echo "If you think that's a bug - please file an issue to https://github.com/bamlab/flashlight/issues"
       exit 1
       ;;
  esac
}

download_flashlight() {
  URL="https://github.com/bamlab/flashlight/releases/latest/download/$FILENAME.zip"
  DOWNLOAD_DIR=$(mktemp -d)

  echo "Downloading $URL..."
  mkdir -p "$INSTALL_DIR" &>/dev/null

  if ! curl --progress-bar --fail -L "$URL" -o "$DOWNLOAD_DIR/$FILENAME.zip"; then
    echo "Download failed.  Check that the release/filename are correct."
    exit 1
  fi

  unzip -q "$DOWNLOAD_DIR/$FILENAME.zip" -d "$DOWNLOAD_DIR"
  mv "$DOWNLOAD_DIR/$FILENAME" "$INSTALL_DIR/flashlight"
  chmod u+x "$INSTALL_DIR/flashlight"
}

check_dependencies() {
  echo "Checking dependencies for the installation script..."
  for dep in curl unzip; do
    if ! hash $dep 2>/dev/null; then
      echo "$dep Missing!"
      exit 1
    fi
  done
}

setup_shell() {
  if [ "$CURRENT_SHELL" = "zsh" ]; then
    CONF_FILE=${ZDOTDIR:-$HOME}/.zshrc
    FLASHLIGHT_PATH='export PATH="'"$INSTALL_DIR"':$PATH"'
  elif [ "$CURRENT_SHELL" = "fish" ]; then
    CONF_FILE=$HOME/.config/fish/conf.d/flashlight.fish
    FLASHLIGHT_PATH='set PATH "'"$INSTALL_DIR"'" $PATH'
  elif [ "$CURRENT_SHELL" = "bash" ]; then
    CONF_FILE=$([ "$OS" = "Darwin" ] && echo "$HOME/.profile" || echo "$HOME/.bashrc")
    FLASHLIGHT_PATH='export PATH="'"$INSTALL_DIR"':$PATH"'
  else
    echo "Could not infer shell type. Please set up manually."
    exit 1
  fi

  if ! command -v flashlight &>/dev/null ; then
    echo "Adding flashlight path to $CONF_FILE"
    echo '' >>$CONF_FILE
    echo '# flashlight' >>$CONF_FILE
    echo $FLASHLIGHT_PATH >>$CONF_FILE
  else
    echo ""
    echo "Flashlight command updated!"
  fi

  echo ""
  echo "In order to apply the changes, open a new terminal or run the following command:"
  echo ""
  echo "  source $CONF_FILE"
}

set_filename
check_dependencies
download_flashlight
if [ "$SKIP_SHELL" != "true" ]; then
  setup_shell
fi
