#!/usr/bin/env bash

# Interactive cd to repo in $PROJECTS_DIR (Defaults to ~/Code)

PROJECTS_DIR=${PROJECTS_DIR:-~/Code}

# Test
project_dirs() {
  find "$PROJECTS_DIR" -maxdepth 1 -type d -not -path "$PROJECTS_DIR" | sort | xargs -L 1 basename
}

query=${1:-''}
query=${query%/} # Remove trailing slash
new_dir=$PROJECTS_DIR/$(project_dirs | fzf-tmux --query "$query" --preview "if [ -f \"${PROJECTS_DIR}\"/{}/README.md ]; then glow \"${PROJECTS_DIR}\"/{}/README.md --style=dark; else ls \"${PROJECTS_DIR}\"/{}; fi")

# If the script executed, we'll just echo back the new directory
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
    echo $new_dir
# If it is sourced however, we'll cd to the new directory
else
  if [[ -n $new_dir ]]; then
    cd $new_dir
  fi
fi

