#!/bin/bash
#                       /usr/local/bin/blog_dirs
# https://crystalfaeries.net/posix/bin/blog_dirs
# celeste:crystalfaery BLOG_DIRS 2021-05-06 19:25:15+00:00
# Our job is to "clean up" directories in the blog tree, except:
# our source code directory /home/celeste/crystalfaeries.net/src
# Remove any "Empty Directory"
#	 or those containing only our README.html symlink
# Ensure each "Active Directory"  has README.html symlink
# Remove any .du.txt or .tree.txt file leftover from dudir
# NOTE:	This should NOT be run between the two times when:
#	the blog script has created the audio directory tree
#	the blog script has uploaded that to our webserver
# therefore, it SHOULD be run upon completion of audio upload.
let help=14	# the line number of this line - 1

case $# in
0 ) 	# we have no options/arguments, therefore do our job:
	for DIR in "$( nice ionice -c 3 find	"${HOME}"/crystalfaeries.net/ -mindepth 1	\( \
	\( -path				"${HOME}"/crystalfaeries.net/src -prune \)	-o \
	\( -type d -empty -exec rmdir {} \; \)							-o \
	\( -type d -print \) \)		|	echo -e )"	# expand the "\n"s
	do
		cd -P -e "${DIR}"		2>> "${HOME}"/.chronicle.log 1>&2	|| continue	#huh?
		rm	.du.txt .tree.txt	2>>/dev/null
		if [ -h README.html ]
		then	# already have README.html, but is there anything else here?
			echo	"$0: non empty directory ${DIR}"	2>> "${HOME}"/.chronicle.log 1>&2
			:	# punt for now
		else	# no link yet, fix it:
			echo	"$0: empty directory ${DIR}"		2>> "${HOME}"/.chronicle.log 1>&2
			ln -s	../README.html				2>> "${HOME}"/.chronicle.log 1>&2
		fi
		find . -mindepth 1 -maxdepth 1 \! -name README.html -type f > /dev/null	# only need returncode
		case $? in
		0)	# there are files here
			:	# No-Op
			;;
		1)	# directory is empty (except for obligatory README.html)
			rm README.html		2>>/dev/null
			rmdir `pwd`		2>>/dev/nulli	# remove the "empty" directory
			;;
		*)	# coding error?
			echo "$0 coding error: $?"				1>&2
			exit	255
			;;
		esac
	done
	exit $?
	;;
1 )  case "${1}" in
--help | -h )
	head -n $help $0
	exit
	;;
--version | -v )
	head -n 4 $0 | tail -n 1
	exit
	;;
* )
	echo "$0 does not cognize ${1}"				1>&2
	exit	255
	;;
    esac
    ;;
* )	# we have multiple options/arguments
	echo "$0 does not accept multiple options/arguments"	1>&2
	exit	255
	;;
esac
echo "$0: programming error"					1>&2
exit 255
