#!/bin/bash
# 2016-05-02 set directories date to most recent file date - rzm
# 2016-12-18 attempt to handle empty directories, failed
# 2016-12-23 fix symlinks 1st
# 2017-03-23 ls -a -> -A; another way to handle empty dirs, still not perfect
# 2017-07-12 args
# 2018-01-22 %l -> %h/%l
# 2018-01-31 omit symlink when looking for the newest file; fix symlinks after directories
# 2018-02-03 omit ls -l summary line
# 2018-02-05 filter out symlinks by using ls -F option
# 2020-10-15 remove *$ from  ls -F  listing
# 2021-09-16 and attempt to fix problem with spaces in dirs
# 2023-04-26 omit non-existent directories, $dirs→"$dirs" finally solves spaces in dirs; 05-01 more final solution, still not perfect

if [ "$1" == "" ]; then dot=.; fi

for dir in "$@" $dot; do
	echo "fixing $dir"
	cd "$dir" || continue

	find . -type d | tac | while read dir; do
		last=`ls -trAF "$dir" | sed 's/\*$//' | egrep -v '@$' | tail -1`
		if [ "$last" == "" ]; then
			last="../"`ls -trA "$dir/.." | tail -2 | head -1`
		fi
		touch -r "$dir/$last" "$dir"
	done

	# fix symlinks' dates
	find . -type l -printf "touch -hr %h/%l %p\n" | sh

	cd ..
done
