#!/usr/bin/env bash
function show() {
  if [[ "$#" -ne 1 ]]; then
    echo "usage: show <prog>" >&2
    return 1
  fi
  case "$(type -t "$1")" in
    alias)
      alias "$1" | bat -pl sh ;;
    keyword|builtin)
      help "$1" ;;
    function)
      declare -f "$1" | bat -l sh ;;
    file)
      local path="$(which "$1")"
      local real="$(realpath "$path")"
      [[ "$path" != "$real" ]] && echo "$path"
      bat "$real" ;;
    "")
      echo "$1 doesn't exist" ;;
  esac
}
complete -c show
function goto() {
  if [[ "$#" -ne 1 ]]; then
    echo "usage: goto <prog>" >&2
    return 1
  fi
  local path="$(which "$1")"
  [[ -z "$path" ]] && return 2
  local real="$(realpath "$path")"
  cd "${real%/*}"
}
complete -c goto
function rl() {
  local l="$1"
  local i=50
  while [[ -L "$l" && $((i--)) > 0 ]]; do
    local n="$(readlink "$l")"
    echo "$l -> $n"
    l="$n"
  done
  [[ -e "$l" ]] && echo "$l" || echo "~nonexistent~"
}
function tmpedit() {
  if [[ "$#" -ne 1 ]]; then
    echo "usage: tmpedit <file>" >&2
    return 1
  fi
  local real="$(realpath "$1")"
  if [[ ! -f "$real" ]]; then
    echo "not found"
    return 2
  fi
  if [[ ! "$real" =~ /nix/store/* ]]; then
    echo "not nix"
    return 3
  fi
  cp --remove-destination "$real" "$1"
  chmod +w "$1"
  $EDITOR "$1"
}
function venv() {
  local dir="$(pwd)"
  while [[ "$dir" != "/" ]]; do
    if [[ -d "$dir/venv" && -f "$dir/venv/bin/activate" ]]; then
      if [[ -v VIRTUAL_ENV ]]; then
        if [[ "$VIRTUAL_ENV" != "$dir/venv" ]]; then
          deactivate
        else
          echo "already active"
          return
        fi
      fi
      . "$dir/venv/bin/activate"
      echo "activated $(realpath --relative-to . "$dir/venv")"
      return
    fi
    dir="$(dirname "$dir")"
  done
  echo "not found"
}

function _comp_rem_binding() {
  local tty="$(stty -g)"
  stty sane
  READLINE_LINE="$(rem "$_comp_rem_arg")"
  READLINE_POINT=${#READLINE_LINE}
  stty "$tty"
}
function _comp_rem() {
  COMPREPLY=""
  _comp_rem_arg="${COMP_WORDS[@]:1}"
  bind -x '"\e[0n": _comp_rem_binding'
  printf '\e[5n' > /dev/tty
}
complete -F _comp_rem rem
