#!/bin/bash -eu
# recent: find files changed recently

. v

usage() {
	echo "usage: recent [-v] [-a] [-d depth] [-D] [-r] [-Q] [-B] [days] [path]"
	echo " e.g.: recent 1 /home"
	echo
	echo "-v     verbose"
	echo "-a     show all files, including hidden files"
	echo "-d     set recursive depth"
	echo "-D     show directories"
	echo "-r     reverse sort"
	echo "-Q     don't use find quick"
	echo "-B     don't insert blank lines"
	echo "-h     show this help"
}

v=""
depth=""
visible_only=(-name '.?*' -prune -o)
reverse=""
type="-type f"
find="find-quick"
insert_blank_lines=1

while getopts "vad:DrQBh" opt; do
	case $opt in
	v)
		# verbose
		v=v
		;;
	a)
		# show all files, including hidden files
		visible_only=()
		;;
	d)
		# set recursive depth
		# use -maxdepth option with find
		depth="-maxdepth $OPTARG"
		;;
	D)
		# show directories
		type=""
		;;
	r)
		# reverse sort
		reverse="-r"
		;;
	Q)
		# don't use find quick
		find="find"
		;;
	B)
		# don't insert blank lines
		insert_blank_lines=""
		;;
	h)
		usage
		exit 0
		;;
	esac
done

shift $((OPTIND-1))

# default to 1 day
days=${1:-1}

# default to current directory
path=${2:-.}

# find files changed in the last $days days

. log

# sort by mtime, oldest first
$v "$find" "$path" $depth "${visible_only[@]}" $type -mtime -$days -printf '%T@\t%p\n' -- |
sort -n $reverse |

# remove leading ./ from filenames
perl -pe 's{([^\t]*\t)\./}{$1}' |

# show the mtime in human-readable format, ISO 8601
awk -F'\t' '{print strftime("%Y-%m-%d %H:%M:%S", $1), $2}' OFS="\t" |

# insert a blank line if more than an hour passed between entries
if [ -n "$insert_blank_lines" ]; then
	awk -F: '
	BEGIN {
		prev_hour = 0
	}
	{
		date_and_hour = $1
		# remove date from hour
		hour = int(substr(date_and_hour, 12))
		if (hour != prev_hour && hour > (prev_hour + 1) % 24) {
			print ""
		}
		print
		prev_hour = hour
	}'
else
	cat
fi |

# pipe through less if stdout is a terminal
less
