#!/bin/bash
#                       /usr/local/bin/cachedir_tags
# https://crystalfaeries.net/posix/bin/cachedir_tags
# celeste:crystalfaery 2019-09-02 03:36:26+00:00

#	This script is intended to be executed from cron, typically backup user's crontab.
#	The job of this script is to locate all CACHEDIR.TAG files in the filesystem,
#	and add their containing directories as excludes below the line:
#       AUTOMATICALLY ADDED EXCLUDES BASED ON CACHEDIR.TAG
#	at the end of the /etc/rsnapshot.conf file.
#	BEWARE: WE ARE AUTO-MODIFYING A CONFIGURATION FILE!
#	QUESTION: do the prune operations print the path pruned? that would be bad!
let help=12
case $# in
0 )
	head -n $(cat -n /etc/rsnapshot.conf				\
	| grep "AUTOMATICALLY ADDED EXCLUDES BASED ON CACHEDIR.TAG"	\
	| cut -f 1)				/etc/rsnapshot.conf	\
	>	/tmp/cachedir_tags.$$.txt
	echo "" >> /tmp/cachedir_tags.$$.txt
	# nice ionice -c 3 find / \(					\
	nice find / \(					\
	\( -path /boot		-prune \) -o				\
	\( -path /dev		-prune \) -o				\
	\( -path /dvd		-prune \) -o				\
	\( -path /lib		-prune \) -o				\
	\( -path /lib64		-prune \) -o				\
	\( -path /live-build	-prune \) -o				\
	\( -path /media		-prune \) -o				\
	\( -path /mnt		-prune \) -o				\
	\( -path /proc		-prune \) -o				\
	\( -path /run		-prune \) -o				\
	\( -path /sbin		-prune \) -o				\
	\( -path /sys		-prune \) -o				\
	\( -path /tmp		-prune \) -o				\
	\( -name CACHEDIR.TAG -print \) \) 2> /dev/null 		\
	| grep -v	/var/cache/rsnapshot/ 				\
	| sed 's/^/exclude	/' 					\
	| sed 's/CACHEDIR.TAG//' 					\
	| sort								\
	>>	/tmp/cachedir_tags.$$.txt
	cat	/tmp/cachedir_tags.$$.txt >	/etc/rsnapshot.conf &&	\
	rm	/tmp/cachedir_tags.$$.txt
	;;
* ) case "${1}" in
    -v | --version )
	head -n 4 $0 | tail -n 1
    ;;
    -h | --help )
	head -n ${help} $0
    ;;
    * )
	echo "$0 does not cognize $@"	1>&2
    ;;
   esac
   ;;
esac
