# MiniServer shell functions, sourced by shell/bashrc

# n opens Neovim in the current directory, or on the files given
n() { if [ "$#" -eq 0 ]; then command nvim . ; else command nvim "$@"; fi; }

# open a file or URL with its default app, detached from the terminal
open() (
  xdg-open "$@" > /dev/null 2>&1 &
)

# compress <dir> makes <dir>.tar.gz (decompress is an alias for tar -xzf)
compress() { tar -czf "${1%/}.tar.gz" "${1%/}"; }

# SSH port forwarding
#   fip <host> <port>...  forward each localhost port to the same port on host
#   dip <port>...         stop forwarding those ports
#   lip                   list active forwards
fip() {
  (( $# < 2 )) && echo "Usage: fip <host> <port1> [port2] ..." && return 1
  local host="$1"
  shift
  for port in "$@"; do
    ssh -f -N -L "${port}:localhost:${port}" "$host" && echo "Forwarding localhost:$port -> $host:$port"
  done
}

dip() {
  (( $# == 0 )) && echo "Usage: dip <port1> [port2] ..." && return 1
  for port in "$@"; do
    pkill -f "ssh.*-L ${port}:localhost:${port}" && echo "Stopped forwarding port $port" || echo "No forwarding on port $port"
  done
}

lip() {
  pgrep -af "ssh.*-L [0-9]+:localhost:[0-9]+" || echo "No active forwards"
}

# Git worktrees
#   ga <branch>  create ../<repo>--<branch> on a new branch and cd into it
#   gd           from inside that worktree, remove it and its branch
ga() {
  if [[ -z "$1" ]]; then
    echo "Usage: ga [branch name]"
    return 1
  fi

  local branch="$1"
  local base="$(basename "$PWD")"
  local wt_path="../${base}--${branch}"

  git worktree add -b "$branch" "$wt_path" || return 1
  command -v mise &> /dev/null && mise trust "$wt_path"
  cd "$wt_path"
}

gd() {
  local cwd base branch root worktree answer

  cwd="$(pwd)"
  worktree="$(basename "$cwd")"

  # split on first `--`
  root="${worktree%%--*}"
  branch="${worktree#*--}"

  # Protect against accidentally nuking a non-worktree directory
  if [[ "$root" == "$worktree" ]]; then
    echo "Not in a worktree made by ga (expected a <repo>--<branch> directory)."
    return 1
  fi

  read -rp "Remove worktree $worktree and branch $branch? [y/N] " answer
  [[ $answer == [yY]* ]] || return 0

  cd "../$root"
  git worktree remove "$cwd" --force || return 1
  git branch -D "$branch"
}
