#!/bin/bash
#                       /usr/local/bin/monitor
#  http://crystalfaeries.net/posix/bin/monitor
# celeste:crystalfaery MONITOR 2017-08-21 00:23:33+00:00
#
# Monitor video and audio files by decreasing size;
#	then ask to "delete" (locally (and copy on my_twin)).
#
#	With no argument, use existing playlist.
#
#  -p	Priority playlist (implies a Reset / Rescan)
#
#  -r	Reset playlist / Rescan disk for candidate files.
#
#  -e	edit exclusion list and playlist
#
#	We assume the youtube playlist of youtubedownload
#	after our scan-generated playlist,
#	in order to pick-up youtube videos downloaded after our scan.
#  -h		help
# --help	help
# NOTE:	Not yet reviewed for XDG compliance, and likely depends on other crystalfaeries.net scripts.
help=22				# lines of header to show as help

#	Configuration
remove=/bin/rm			# delete only locally (in case off-line or stand-alone)
remove=/usr/local/bin/delete	# delete both locally and on my_twin
ip_address=192.168.1.196	# LAN IP# of streamripper host if it's not me
ip_address=127.0.0.1		# localhost if alone (last one wins)
alert="/usr/share/sounds/gnome/default/alerts/drip.ogg"	# alert sound
 diryou=/home/downloads/youtube.com/			# youtubes directory
 playou=/home/downloads/youtube.com/.playou.txt		# youtubes playlist
playlist=$HOME/documents/playlists/txt/monitor.txt	# playlist to monitor
 pbackup=$HOME/documents/playlists/txt/monitor.p.txt	# playlist to monitor
 rbackup=$HOME/documents/playlists/txt/monitor.r.txt	# playlist to monitor
  viewed=$HOME/.dush.media.txt			# list of files already viewed, to skip
unhardlink "${viewed}"	# before any usage, in case we fdeduped thereby uniting ${viewed} + ${viewed}-

#	Arguments
false
priority=$?				# default no priority
while	[ $# -ne 0 ]
do
case "$1" in
--help)
	head -n $help $0		1>&2	# help message
	exit 0
	;;
-h)
	head -n $help $0		1>&2	# help message
	exit 0
	;;
-p)
	true
	priority=$?			# priority implies:
	cp /dev/null "$playlist"	# reset playlist
	shift
	;;
-r)
	cp /dev/null "$playlist"	# reset playlist
	shift
	;;
-e)
	# wash the sorted ${viewed} list of any deleted files and review in editor
	sort -u ${viewed} >	${viewed}-	|| exit -1
	cp /dev/null		${viewed}	|| exit -1
	while read f
	do
		if [ -f		"${f}" ]
		then # file exists
			echo	${f} >> ${viewed}
		fi
	done < ${viewed}-			# keep old version as backup
	vi "$viewed" "$playlist" "$viewed"	# edit viewed list and play list
	shift
	exit
	;;
*)
	echo "$0 does not cognize $@"	1>&2	# error message
	echo "try: -h or --help"	1>&2	# error message
	exit -1
	;;
esac
done

#       Initialization
cd	# must be in user's home directory for "delete" to work (until it is rewritten)
appname="$(basename $0)"
tmpfile="$(mktemp /tmp/${appname}.XXXXXX)" || exit 1
trap "let exitval=$?; rm -f $tmpfile; exit $exitval" 0 1 2 15
touch "$viewed" "$viewed"-      # keep a record of what we view so we only see each file once, and backup copy

#	Monitor streamrips or largest media

if [ \! -s $playlist ]
then	# use old playlist if it exists, otherwise construct a new one:
	if [ $priority -eq 0 ]
	then	# priority playlist (this playlist presumes NO remote files, e.g. http://domain.net/file.ogg)
		find /home/audio/devaudio/ /home/video/devideo/ \( \( -iname '*.avi' \) -o \( -iname '*.dsf' \) -o \( -iname '*.flac' \) -o \( -iname '*.flv' \) -o \( -iname '*.m4?' \) -o \( -iname '*.mkv' \) -o \( -iname '*.mov' \) -o \( -iname '*.mp?' \) -o \( -iname '*.og?' \) -o \( -iname '*.opus' \) -o \( -iname '*.ram' \) -o \( -iname '*.rm*' \) -o \( -iname '*.spx' \) -o \( -iname '*.swf' \) -o \( -iname '*.vob' \) -o \( -iname '*.wav' \) -o \( -iname '*.webm' \) -o \( -iname '*.wm?' \) \) -type f -print 2>/dev/null > $tmpfile
		cat $tmpfile | xargs du | sort -nr | cut -f 2- \
		>					$playlist	# generate updated playlist by decreasing size
		rsync -auvzH $playlist $pbackup
		for f in $(cat $viewed);do
			grep -v "$f"			$playlist \
			>	/tmp/monitor.txt
			mv	/tmp/monitor.txt	$playlist
		done
	else	# regular playlist
		# Find all audio+video media by decreasing size:
		find $HOME/documents/ /home/audio/ /home/video/ /home/crystalfaeries.net/ /home/downloads/ -path /home/downloads/crystalfaeries.net -prune -o -path /home/audio/devaudio -prune -o -path /home/video/devideo -prune -o -path /home/audio/devaudio -prune -o -path /home/video/devideo -prune -o \( \( -iname '*.avi' \) -o \( -iname '*.dsf' \) -o \( -iname '*.flac' \) -o \( -iname '*.flv' \) -o \( -iname '*.m4?' \) -o \( -iname '*.mkv' \) -o \( -iname '*.mov' \) -o \( -iname '*.mp?' \) -o \( -iname '*.og?' \) -o \( -iname '*.opus' \) -o \( -iname '*.ram' \) -o \( -iname '*.rm*' \) -o \( -iname '*.spx' \) -o \( -iname '*.swf' \) -o \( -iname '*.vob' \) -o \( -iname '*.wav' \) -o \( -iname '*.webm' \) -o \( -iname '*.wm?' \) \) -type f -print 2>/dev/null \
		| xargs du | sort -nr | cut -f2-	>> $playlist	# generate updated playlist by decreasing size
		rsync -auvzH $playlist $rbackup						# backup the full list then prune pre-viewed items
		while read f
		do
			grep -v "${f}"			   $playlist > \
				/tmp/monitor.txt
			mv	/tmp/monitor.txt	   $playlist
		done < ${viewed}
	fi
fi

# play them and ask if they should be removed ("y*" will remove)
# interlacing with playing local media files, we scan a port range of
# streamrip relay ports 8001-8007 and 8009
# in case a cron scheduled streamrip has activated
let sleep=1
while sleep $sleep
do
	# ports 80, 8008, 8080 are reserved for various web servers: http://crystalfaeries.net/servers.html
	# we have allocated 8001-8007 for streamrips which are of continuious streams, and 8009 for KKCR programs
	for   port in 8009 {8007..8001}
	do	# iterate the relay channels for any streamripper relays
		mplayer http://$ip_address:$port
	done
	mplayer http://127.0.0.1:8000/stream.ogg		# IceCast2 Stream
	file="$(head -n 1 "$playlist" 2>/dev/null)"		# the next largest media file
	if [ "X$file" == "X" ]
	then	# null line
	    if [ -s "$playlist" ]
	    then	# null line
		rm				"$playlist"-	# does not like overwrites if on NAS
		mv		"$playlist"	"$playlist"-	# does not like overwrites if on NAS
		tail -n +2	"$playlist"- >	"$playlist" 2>/dev/null	# update the playlist
	    else # We assume the youtube playlist of youtubedownload.`hostname`
		if [ -s "$playou" ]
		then
			cp		"$playou"	"$playlist"
			cp /dev/null	"$playou"
		else
			exec monitor -r	# rescan
		fi
	    fi
	else	# (dis)play it and ask to remove it
	    grep       "$file" "$viewed" >& /dev/null
	    if [[ $? -ne 0 ]]
	    then
	    	if [ -r "$file" ]
	    	then
		    echo "$file" | grep '.jpg$' > /dev/null 2>&1
	    	    if [[ $? -eq 0 ]]
		    then					# display the album artwork
			gwenview "$file" || gthumb "$file"
		    else					# play the media
			mplayer "$alert" > /dev/null 2>&1 # warn the user of window popping up
			sleep 2
			echo "$file" | grep '.mkv$' > /dev/null 2>&1
			if [[ $? -eq 0 ]]
			then					# we have a .mkv
				echo "Launching VLC for $file ..."
	  			vlc -f	"$file"	\
				&& let sleep=1				\
				|| let sleep=$sleep+$sleep	# binary back-off upon failure
			else
			    echo "$file" | grep '.webm$' > /dev/null 2>&1
			    if [[ $? -eq 0 ]]
			    then				# we have a .webm
				echo "Launching VLC for $file ..."
	  			vlc -f	"$file"	\
				&& let sleep=1				\
				|| let sleep=$sleep+$sleep	# binary back-off upon failure
			    else				# a media file mplayer can play
			    	echo "$file" | grep '.swf$' > /dev/null 2>&1
			    	if [[ $? -eq 0 ]]
			    	then				# we have a .swf
					echo "Launching klash for $file ..."
	  				klash --fullscreen	"$file"	\
					&& let sleep=1				\
					|| let sleep=$sleep+$sleep	# binary back-off upon failure
			    	else				# a media file mplayer can play
	  				mplayer	-fs -idx -loop 0 "$file"	\
					&& let sleep=1				\
					|| let sleep=$sleep+$sleep	# binary back-off upon failure
				fi
			    fi
			fi
	    	    fi
		    echo "CrystalFaeries.NET usage:"
		    grep $(basename "${file}") /home/crystalfaeries.net/src/* /home/crystalfaeries.net/src/.201*
		    df --full	# show disk usage and all known copies of this file:
		    find /home/{audio,video}/ -samefile			"${file}" -exec ls -Flad {} \;  > /tmp/$$.txt
		    find /home/{audio,video}/ -iname "$(basename	  $file)" -exec ls -Flad {} \; >> /tmp/$$.txt
		    sort -u										< /tmp/$$.txt
		    $remove -i			"$file"	# do you want me to delete *this* copy?
		    if [ -r "$file" ]
		    then	# if file viewed and kept, mark as seen to hide it
		    	echo	"$file" >>	$viewed
		    else	# if file viewed and deleted, unmark as seen
		    	grep -v	"$file"		$viewed >	$tmpfile
		    	mv					$tmpfile \
		    				$viewed
		    fi
	    	fi
	    fi
	    rm                      		"$playlist"-	# does not like overwrites if on NAS
	    mv			"$playlist"	"$playlist"-	# does not like overwrites if on NAS
	    grep -v "$file"	"$playlist"- >	"$playlist"	# update the playlist
	fi
done
exit	-1	# error exit

while read f
do
	grep -v "${f}"			documents/playlists/txt/monitor.txt > \
		/tmp/monitor.txt
	mv	/tmp/monitor.txt	documents/playlists/txt/monitor.txt
done < "${viewed}"

exit	$?	#######	CODE BELOW IS IN DEVELOPMENT	#######
# generate combined playlist by size
cp	/dev/null	/tmp/$$.media.txt
for extension in flv mkv mov mp4 ogv rm wav ogg flac m4a mp3
do	# list the media files which live on the webserver
	grep "${extension}$"	/home/crystalfaeries.net/.du.txt	\
|	sed 's/	\./	\/home\/crystalfaeries.net/;s/crystalfaeries.net\/audio/audio\/www/;s/crystalfaeries.net\/video/video\/www/'	\
>>	/tmp/$$.media.txt	# transformed to look like local files for size sorting purposes
done
# calculate sizes for files already in other playlists
cat	~/documents/playlists/txt/monitor*txt{,-,+}	\
|	sort	-u	\
|	xargs	du	>>	/tmp/$$.media.txt
# now with a single combined file-list, do the reverse size sort
cat	/tmp/$$.media.txt	\
|	sort	-u	\
|	sort	-rn	>>	~/documents/playlists/txt/monitor.txt+


syntax highlighted by Code2HTML, v. 0.9.1