#!/bin/sh

#To add more caches, add a newline to this string and follow the existing name:path format 
#Edit create_new to change find behaviour
cache_info="home:$HOME"
HOME=/home/immanuel
XDG_CACHE_HOME="$HOME/.cache"

init() {
	mkdir -p $XDG_CACHE_HOME/mru
	create_new "$1"
	mv "$file.new" "$file"
}

get_cache_path() {
	if [ -z "$1" ]; then printf "no arg to get_cache_path\n" 1>&2; exit; fi
	path="$(printf $cache_info | grep "^$1" - | cut -d: -f2)"
	if [ -z "$path" ]; then printf "invalid cache name: $1\n" 1>&2; exit; fi
	printf "$path"
}

create_new() {
	file=$XDG_CACHE_HOME/mru/"$1"
	path=$(get_cache_path "$1")

	find $path -type f -not \( -path '*/.*/*' -o -path '*node_modules/*' -o \
		-path '*Backups/my-plugins*' -o -path '*.sw[po]' \) -printf \
		'%TY-%Tm-%Td\t%TT\t%p\n' | sort -r > $file'.new'
}
update() {
	clean
	name="$1"
	if [ -z "$1" ]; then
		name='home'
	fi
	create_new "$name"
}

output() {
	if [ -z "$1" ]; then
		cat $XDG_CACHE_HOME/mru/home; else cat "$XDG_CACHE_HOME/mru/$1";
	fi
}

list() {
	output "$1" | cut -f3
}

insert() {
	if [ -z "$1" ]; then printf "No path given\n" 1>&2; exit; fi
	cache_name=${1+'home'}
	cache_path=$(get_cache_path "$cache_name")

	file_path=$(realpath "$1")	
	if [ -e "$file_path" ]; then
	# sed "0,\|.*\t.*\t$file_path|s|||" $XDG_CACHE_HOME/mru/$cache_name
		sed -e "0,\|.*\t.*\t$file_path|d" -e "1s;^;$(date '+%Y-%m-%d%t%T')\t$file_path\n;" <$XDG_CACHE_HOME/mru/$cache_name \
			>$XDG_CACHE_HOME/mru/$cache_name.insert$$
		mv $XDG_CACHE_HOME/mru/$cache_name.insert$$ $XDG_CACHE_HOME/mru/$cache_name 
	else
		sed "0,\|.*\t.*\t$file_path|d" <$XDG_CACHE_HOME/mru/$cache_name \
			>$XDG_CACHE_HOME/mru/$cache_name.insert$$
		mv $XDG_CACHE_HOME/mru/$cache_name.insert$$ $XDG_CACHE_HOME/mru/$cache_name 

	fi
}

clean() {
	rm $XDG_CACHE_HOME/mru/*.{insert,new}*
}

case "$1" in 
	init) init "$2";;
	update) update $2;;
	output) output "$2";;
	list) list "$2";;
	insert) insert "$2" "$3";;
	clean) clean;;
esac