#!/bin/bash
#
# Plugin: cd_rc
# Description: Replaces vanilla cd with the Bash Directory Stack with custom formatting and defines common directory changing settings.
# Author: Anon
# Date: 2024
# Version: 1.0
# Source:
#   mirror 1: http://bis64wqhh3louusbd45iyj76kmn4rzw5ysawyan5bkxwyzihj67c5lid.onion/anon/cd_rc
#   mirror 2: https://github.com/agvxov/cd_rc.git

alias cd="PushdAlias"
alias popd="PopdAlias"
alias dirs="DirsAlias"
alias cdh="cd ~"
alias cdu="cdUp"
alias pop="popd"

alias cd..="cd .."	# people like this for some reason

function mkdircd() {
	mkdir -p "$@" && eval cd "\"\$$#\"";
}
function cdUp() {
	if [[ $# -eq 0 ]]; then
		cd ..
		return
	fi
	for ((i=0 ; i <= $# ; i++)); do
		cd ..
	done
}
function PushdAlias() {
	if [ -d "$1" ]; then
		\pushd "$1" > /dev/null
		dirs
	else
		SPWD=$PWD
		\pushd "$@" > /dev/null
		[ $SPWD != $PWD ] && dirs
	fi
}
function PopdAlias() {
	if [[ $1 =~ ^[0-9]+$ ]]; then
		for ((i=0 ; i < $1 ; i++)); do
			\popd > /dev/null
		done
		dirs
		return
	fi
	\popd "$@" > /dev/null && dirs
}
function DirsAlias() {
	if [ $# == 0 ]; then
		\dirs -p | awk -v ln=0 \
			'{
				if (system("test -d \"$(echo " $0 ")\""))
				  { color="31"; }
				  else
				  { color="36"; }
				printf("\033[1;%sm%2d: \033[m%s\n", color, ln++, $0);
			}'
	else
		\dirs "$@"
	fi
}


shopt -s cdspell		# If set, minor errors in the spelling of a directory component in a cd 
			    		# command will be corrected. The errors checked for are transposed characters, 
			    		# a missing character, and a character too many.


