#!/bin/bash
# ~/bin/steal-from-cache.sh last edited 2021-02-22

[ -z "$1" ] && printf "Usage:	$(basename $0) cache-directory target-directory
	copies certain types of file from a cache directory (as soon as
	they are closed) to the target directory. The new filenames are
	are timestamps, referring to the time the file was just closed.
	A random pair of letters is appended for uniqueness.
	The identification of TS files depends on a local ~/.magic file.
	The script can be stopped by removing the file called 0 from the
	target-directory. It may be rerun using an existing target.\n" 1>&2 && exit 1

Theletters='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'

Sourcedir="${1%/}"
[ ! -d "$Sourcedir" ] && printf '%s\n' "Directory $Sourcedir not found!" && exit 2
[ ! -r "$Sourcedir" ] && printf '%s\n' "Directory $Sourcedir not readable!" && exit 3

Targetdir="${2%/}"
if [ ! -d "$Targetdir" ]; then
    if ! mkdir -p "$Targetdir"; then
	printf '%s\n' "mkdir $Targetdir failed" && exit 4
    fi
fi
if [ ! -w "$Targetdir" ]; then
    printf '%s\n' "Directory $Targetdir not writeable!" && exit 5
fi
touch "$Targetdir/0"
chmod a+wrx "$Targetdir"

inotifywait -m -e close_write --format "%f" "$Sourcedir" | \
    while IFS=$'\n' read Filename ; do
	#printf '•%s\n' "$Filename" #
	[ ! -f "$Targetdir/0" ] && break
	Thefiletype="$(file -b "$Sourcedir/$Filename")"
	#printf ' %s (%s)\n' "$Filename" "$Thefiletype" #
	case "$Thefiletype" in
	    *GIF* )
		Suffix="gif"
		;;
	    *JPEG* )
		Suffix="jpg"
		;;
	    *PNG* )
		Suffix="png"
		;;
	    *"Web/P image"* )
		Suffix="web"
		;;
	    *"ISO Media, MP4"* )
		Suffix="mp4"
		;;
	    *MPEG* )
		Suffix="mpg"
		;;
	    *WebM* )
		Suffix="wbm"
		;;
	    *"TS transport"* )
		Suffix="ts"
		;;
	    * )
		continue
		;;
	esac
	Fullname="$Targetdir/$(date +'%Y-%m-%d-%H%M%S-%02N')${Theletters:((RANDOM % 52)):1}${Theletters:((RANDOM % 52)):1}.$Suffix"
	cp -ip "$Sourcedir/$Filename" "$Fullname"
	chmod a+r "$Fullname"
	printf '%s %s\n' "$Filename" "$Fullname"
    done

unset Theletters Sourcedir Targetdir Filename Thefiletype Suffix Fullname

#
