#!/bin/bash

function findbydate_output
{
	local FILE="$1"
	local LAST_DATA_MODIFICATION=$(stat -c '%Y' "$FILE")
	local LAST_DATA_MODIFICATION_YYYYMMDD_HHMMSS=$(date --date=@$LAST_DATA_MODIFICATION +%Y%m%d_%H%M%S)
	echo "$LAST_DATA_MODIFICATION_YYYYMMDD_HHMMSS $FILE"
}

if [ $# -ne 1 -a $# -ne 2 ]; then
	echo "Find and output files by date in lexicographic increasing (or decreasing -r) order"
	echo "  -n  Use newline character as a delimiter instead of null for legacy versions of sort"
	echo "usage:"
	echo "findbydate.sh [-r] [-n] DIR"
	exit 1
fi

if [ "$1" = '-r' ]; then
	SORT_REVERSE="-r"
	shift
fi

NULLLINE=true
if ! cut -z --version >/dev/null 2>&1; then
	NULLLINE=false
fi

if [ "$1" = '-n' ]; then
	NULLLINE=false
	shift
fi

DIR="$1"

if $NULLLINE; then
	find "$DIR" -printf "%T@ %p\0" | sort $SORT_REVERSE -n -z | cut -d ' ' -f 2- -z | \
		while IFS= read -r -d '' FILE; do
			findbydate_output "$FILE"
		done
else
	find "$DIR" -printf "%T@ %p\n" | sort $SORT_REVERSE -n | cut -d ' ' -f 2- | \
		while read -r FILE; do
			#echo "$FILE"
			findbydate_output "$FILE"
		done
fi
