#!/bin/bash

__switch_repos() {
  local repo_name="$1"

  if [ "${repo_name}" = "-ls" ]; then
    if [ -d ~/Projects ]; then
      find -L ~/Projects -type d -depth 1 -maxdepth 1 -exec basename {} +
    fi
    if [ -d ~/Development ]; then
      find -L ~/Development -maxdepth 3 -name '.git' | sed -E 's/(.*)\/\.git/\1/' | xargs basename
    fi
    return
  fi

  if [ -z "${repo_name}" ]; then
    local repo_root=$(git rev-parse --show-toplevel 2>&1)
    if [[ "${repo_root}" == fatal:* ]]; then
      echo "Could not find repo root. Are you in a git repo?"
    else
      cd "${repo_root}"
    fi
    return
  fi

  # If repo name is given, find full path to repo
    repo_path=`find -L ~/Projects -type d -depth 1 -maxdepth 1 -name "${repo_name}" | head -n 1`
  if [ -z "${repo_path}" ]; then
    repo_path=`find -L ~/Development -maxdepth 3 -path "*${repo_name}/.git" | xargs -n 1 dirname | head -n 1`
  fi
  if [ -z "${repo_path}" ]; then
    echo "No such repo: \"$1\""
  else
    cd "${repo_path}"
    if [ -n "${VIRTUAL_ENV}" ]; then
      # Exit current virtualenv, if any
      deactivate
    fi
    if type workon &> /dev/null && workon | grep -Fxq "${repo_name}"; then
      # If there is a virtualenvwrapper virtualenv with an exact match, activate it
      workon "${repo_name}"
    elif [ -d venv -a -f venv/bin/activate ]; then
      # If there is a venv folder in the repo and it's a virtualenv, activate it
      source venv/bin/activate
    fi
  fi
}

__switch_repos "$1"
