#!/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

dirs="$*"
if [ "$dirs" == "" ]; then dirs=.; fi

for dir in $dirs; do
	echo fixing $dir
	cd $dir

	find . -type d | tac | while read dir; do
		last=`ls -ltrA "$dir" | egrep -v ' -> ' | awk '{ print $NF }' | 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
