#!/bin/bash
#                       /usr/local/bin/dush
# https://crystalfaeries.net/posix/bin/dush
# celeste@crystalfaeries.net DUSH 2018-08-15 22:43:36+00:00
# (douche (Disk Usage douching)):			# review files by size decreasing
#
# 2011-03-09 02:43:58+00:00 dush.1
# 2011-05-20 22:57:50+00:00 beginning development of a new recursive version which tracks per directory
#
# Future / ToDo:
#
# Add display of directories and .pdf files
# Then change generation of .du files to add directories as summary size and .pdf files, but not recurse subdirs
#
# THIS IS NO LONGER TRUE:
# we ignore .pdf files because we handle those separately system wide via /usr/local/bin/pdfs
# we could integrate the pdf handling code into this script to find .pdf files both ways
#
# if the variable "file" contains a file's basename,
# we can substitute the existing extension to be ".ext" by:
# ${file%.*}.ext
# now, how do we use this to compare
# the existing filename "$f" with the pattern "*.pdf"?

#	Traps and Temporary files:
exitval=1		#default to error condition because we have not yet chosen to intend to exit
appname="$(basename $0)"
tmpfile=$(mktemp /tmp/${appname}.XXXXXX) || exit $exitval
trap "rm -f $tmpfile ; exit $exitval" 0 1 2 15

####################################################################################################
#                                                                                                  #
#	EEK I hacked the code and did not complete the hack so now it is broken :-(                #
#                                                                                                  #
####################################################################################################

exit -1	# DANGER: INCOMPLETE CODE BELOW

#	Working Directory
cd $HOME/crystalfaeries.net/audio/						# work at the relative root level of the Music itself
touch .music.txt					# keep a record of what we hear so we only hear each file once

# generate current index files
nice find . -name .du.txt \( -ctime +32 -o -mtime +32 \) -exec rm {} \; # ensure our index files are relatively recent
if [ -f .du.txt ]
then
	touch .dush.txt					# keep a record of what we view so we only see each file once
	if [ ! -s .du.txt ]				# if empty, regenerate
	then
		echo "Generating index as of `now` for `pwd`, a process which could take a long time..."
		nice find . -type f \! -iname '*.pdf' \! -name '.du*.txt' -exec du {} \; 2>/dev/null | sort -rn | cut -f 2- | sed 's/^\.\///' > .du.txt
	fi
else
	touch .dush.txt					# keep a record of what we view so we only see each file once
	echo "Generating index as of `now` for `pwd`, a process which could take a long time..."
	nice find . -type f \! -iname "*.pdf" \! -name ".du*.txt" -exec du {} \; 2>/dev/null | sort -rn | cut -f 2- | sed 's/^\.\///' > .du.txt
fi

#iterate through the index showing anything not already seen
while [ -s .du.txt ] ; do
	f=$(head -n 1 .du.txt)
	tail -n +2    .du.txt >	 /tmp/$$.du.txt
	mv     /tmp/$$.du.txt		.du.txt
	if [ -s .dush.txt ]
	then	# there are entries in .dush.txt to filter out
		grep "$f" .dush.txt > /dev/null
		if [[ $? = 0 ]]
		then
			echo previewed:	$f
		else
		if [ -f "$f" ]
		then
			echo viewing:	$f
							# display the file and ask to delete
			let media=1			# presume not a media file unless we match extension
			let pdf=1			# presume not a portable document file unless we match extension
			let picture=1			# presume not a picture file unless we match extension
			file="$(basename $f)"		# base file name
			suffix="$(echo $file | sed 's/^.*\.//')"
			for extension in asx avi dsf flac flv m4a m4v mov mp1 mp2 mp3 mp4 mpeg mpg ogg ogv ra ram rm video VOB wav wma wmv ; do
				if [ "$suffix" == "$extension" ]
					then let media=0
				fi
			done
			for extension in pdf PDF ; do
				if [ "$suffix" == "$extension" ]
					then let pdf=0
				fi
			done
			for extension in gif GIF png PNG pnm PNM jpg JPG ;do
				if [ "$suffix" == "$extension" ]
					then let picture=0
				fi
			done
			if [[ $media -eq 0 ]]
			then
				mplayer -fs	"$f" &&	\
				rm -i	"$f";		# you want I should remove this file?
			elif [[ $pdf -eq 0 ]]
			then
				/usr/bin/epdfview	"$f" &&	\
				rm -i	"$f";		# you want I should remove this file?
			elif [[ $picture -eq 0 ]]
			then
				/usr/bin/gwenview	"$f" &&	\
				rm -i	"$f";		# you want I should remove this file?
			else	
				/usr/bin/konqueror	"$f" &&	\
				rm -i	"$f";		# you want I should remove this file?
			fi
			if [ -f		"$f" ]
			then				# user did not choose to remove the file
				echo "$f" >> .dush.txt	# record that we viewed the file
				echo viewed:	"$f"
				sort -u .dush.txt > "$tmpfile" && mv "$tmpfile" .dush.txt
			else				# user did     choose to remove the file
				echo removed:	"$f"
			fi
		fi
		fi
	else	# there are no entries in .dush.txt to filter out
		if [ -f "$f" ]
		then
			echo viewing:	$f
							# display the file and ask to delete
			let media=1			# presume not a media file unless we match extension
			let pdf=1			# presume not a portable document file unless we match extension
			let picture=1			# presume not a picture file unless we match extension
			file="$(basename $f)"		# base file name
			suffix="$(echo $file | sed 's/^.*\.//')"
			for extension in asx avi dsf flac flv m4a m4v mov mp1 mp2 mp3 mp4 mpeg mpg ogg ogv ra ram rm video VOB wav wma wmv ; do
				if [ "$suffix" == "$extension" ]
					then let media=0
				fi
			done
			for extension in pdf PDF ; do
				if [ "$suffix" == "$extension" ]
					then let pdf=0
				fi
			done
			for extension in gif GIF png PNG pnm PNM jpg JPG ;do
				if [ "$suffix" == "$extension" ]
					then let picture=0
				fi
			done
			if [[ $media -eq 0 ]]
			then
				mplayer -fs	"$f" &&	\
				rm -i	"$f";		# you want I should remove this file?
			elif [[ $pdf -eq 0 ]]
			then
				/usr/bin/epdfview	"$f" &&	\
				rm -i	"$f";		# you want I should remove this file?
			elif [[ $picture -eq 0 ]]
			then
				/usr/bin/gwenview	"$f" &&	\
				rm -i	"$f";		# you want I should remove this file?
			else
				/usr/bin/konqueror	"$f" &&	\
				rm -i	"$f";		# you want I should remove this file?
			fi
			if [ -f		"$f" ]
			then				# user did not choose to remove the file
				echo "$f" >> .dush.txt	# record that we viewed the file
				echo viewed:	"$f"
				sort -u .dush.txt > "$tmpfile" && mv "$tmpfile" .dush.txt
			else				# user did     choose to remove the file
				echo removed:	"$f"
			fi
		fi
	fi
done
exit	$exitval	#######	DEBUGGING EXIT	#######	CODE BELOW STILL BEING (RE)WRITTEN	#######

#now have multiple chat logs for multiple worlds, so we need to update / upgrade

#	Playlist for streaming URLs:
	playlist=/home/www/playlists/shoutcast2sl.txt

#	userland crontab entry (edit according to your Second Life(TM) and other virtual world viewers) example:
# 04 2 * * * grep "Starting internet stream: " $HOME/.firestorm/logs/Firestorm.log | sed 's/^.*Starting internet stream: //' >> $HOME/Music/playlists/$playlist

#


#	Audio Player and Alert Sound:
	alert="/usr/share/sounds/gnome/default/alerts/bark.ogg"
	player='/usr/bin/mplayer'
	player_options='-fs'
	porn_player='/usr/bin/xine --fullscreen --loop=loop --session volume=69'
	exitval=$("$player" "$alert") > /dev/null

#
#	HELP
#
if [ "$1" = "-h" ]
then
	echo "$(basename $0) Usage:"
	echo "If you don't skip them with the -s flag, then first we play local files,"
	echo "and after each file we give you an opportunity to enter 'rm' to remove that file,"
	echo "or enter 'de' to defer that file, or enter 'ed' to edit that file in audacity."
	echo "Yes, the script should be updated to choose like kino vs audacity for videos."
	echo "Changing    stations is as easy as typing:    'q<enter>'"
	echo "To remove a station from your playlist, type: 'qrm<enter>'"
	echo "To stop listening, type:                      'q^C>'"
	echo "To pause or resume listening, type:         ' '"
	echo "Some streams may not be resumable, so you 'resume' the next 'station'."
	exit 0
fi

#
#	STREAMS ONLY FLAG?
#
let streams_only=1 # false
if [ -n "$1" ]	# any arguments on command line?
then
	if [ "$1" = "-s" ] # yes, "-s" tells us to play only streams_only sources
	then
		let streams_only=0 # true
		shift
	fi
fi

#
#	1 Infinite Loop (ref: where is the flagpole holding the pirate flag in "Pirates of Silicon Valley"? in the center of)
#
#cd $HOME/crystalfaeries.net/audio/						# work at the relative root level of the Music itself
#touch .music.txt					# keep a record of what we hear so we only hear each file once
while sleep 1;do	#loop forever, presuming concurrency with Second Life (TM) and streamripper

    if [ $streams_only = 0 ]
    then
	echo Playing Streams only, as requested
    else
	echo Playing Local Files followed by Streams, as requested
#
#	PLAY LOCAL FILES FIRST
#

# build the list of existing files
	cp	/dev/null			   		   "$tmpfile"
	for	   directories	in /media/cdrom $HOME/Music $HOME/video /media /mnt /opt ~/Downloads /usr/local/src /home/www	; do
		for extensions	in .asx .avi .flac .flv .mov .mp1 .mp2 .mp3 .mp4 .mpg .ogg .ra .rm .ram .wma .wmv	; do
			nice find $directories -iname "*$extensions" -exec du {} \; 2>/dev/null | grep -v kartrons_whores >> "$tmpfile"
		done
	done
# in decreasing size order
	sort -rn "$tmpfile" | cut -f 2- >	/tmp/$$.music.txt
	mv					/tmp/$$.music.txt	"$tmpfile"
# clean the list of pre-viewed files
	sort -u   .music.txt > /tmp/$$.music.txt
	mv /tmp/$$.music.txt          .music.txt
# iterate, iterate, dance to the music...
	for f in $(cat "$tmpfile");do
	    if [ -s "$f" ]
	    then	# the audio file has content
		if [ -s .music.txt ]
		then	# there are entries in .music.txt to filter out
			grep "$f" .music.txt > /dev/null
			if [[ $? = 0 ]]
			then
				echo PREHEARD:       $f
			else
				echo HEARING_:        $f
								# play the file and ask to delete
				echo -n "Disposition: ('de' to defer, 'ed' to edit, 'rm' to remove/mute, else KEEP)?: "
				read a
				if [ "$a" = "rm" ]
				then
					rm "$f"
				elif [ "$a" = "ed" ]
				then
					audacity "$f"
				else
					echo "KEPT:           $f"
				fi
				if [ -f		"$f" ]
				then				# user did not choose to remove the file
					if [ "$a" = "de" ]
					then
						echo DEFERRED:     "$f"
					else
						echo "$f" >> .music.txt	# record that we heard the file
						sort -u   .music.txt > /tmp/$$.music.txt
						mv /tmp/$$.music.txt          .music.txt
						echo HEARD+KEPT:     "$f"
					fi
				else				# user did     choose to remove the file
					echo REMOVED:        "$f"
				fi
			fi
		else	# there are no entries in .music.txt to filter out
				echo HEARING_:        $f
								# play the file and ask to delete
				exitval=$("$player" "$player_options" "$f")
				echo -n "Disposition: ('de' to defer, 'ed' to edit, 'rm' to remove/mute, else KEEP)?: "
				read a
				if [ "$a" = "rm" ]
				then
					rm "$f"
				elif [ "$a" = "ed" ]
				then
					audacity "$f"
				else
					echo "KEPT:           $f"
				fi
				if [ -f		"$f" ]
				then				# user did not choose to remove the file
					if [ "$a" = "de" ]
					then
						echo DEFERRED:     "$f"
					else
						echo "$f" >> .music.txt	# record that we heard the file
						sort -u   .music.txt > /tmp/$$.music.txt
						mv /tmp/$$.music.txt          .music.txt
						echo HEARD+KEPT:     "$f"
					fi
				else				# user did     choose to remove the file
					echo REMOVED:        "$f"
				fi
		fi
	    else	# the audio file is null, probably a gcn talk show awaiting download
		echo NULLFILE:       $f
	    fi
	done
    fi	# end of local files
#
#	UPDATE STREAMS PLAYLIST FROM SECOND LIFE (TM) SHOUTCAST2SL JUKEBOX
#
if [ -d "$HOME"/chatlogs ]
then
	if [ -f "$HOME"/chatlogs/chat.txt ]
	then
		echo "Good:	I found your chatlog."
	else
		echo "I can not find your chatlog, so please:"
		echo "ln -s "$HOME"/.secondlife/avatar_name/ "$HOME"/chatlogs"
		echo "I do not presume which 'avatar name' you use."
		exit 1
	fi
else
	echo "I can not find your chatlogs, so please:"
	echo " ln -s "$HOME"/.secondlife/avatar_name/ "$HOME"/chatlogs"
	echo "I do not presume which 'avatar name' you use."
	exit 1
fi
if [ -d $HOME/Music ]
then
	if [ -d $HOME/Music/playlists ]
	then
		echo "Good:	playlists directory found."
	else
		mkdir -p $HOME/Music/playlists
		echo "Good:	playlists directory created."
	fi
else
	mkdir -p $HOME/Music/playlists
	echo "Good:	playlists directory created."
fi
	echo "Good:	Refreshing Playlist from Second Life (TM) Public Chatlog..."
	if [ -f		playlists/$playlist ]
	then
		cp	playlists/$playlist							/tmp/$playlist.$$
	else
		touch										/tmp/$playlist.$$
	fi
	grep "SHOUTCAST2SL JUKEBOX" "$HOME"/chatlogs/chat.txt | cut -c 64- | sort -u | grep http >> 	/tmp/$playlist.$$
	sort -u			      /tmp/$playlist.$$	>			   		playlists/$playlist
	rm			      /tmp/$playlist.$$
	echo "Good:	Pruning the streams previously removed from the playlist:"
	if [ -f		playlists/."$playlist" ]
	then
		if [ -z playlists/."$playlist" ]
		then
			echo "OK:	Empty Mute List."
		else
			echo -n "Good:	Processing Mute List"
			for u in $(cat playlists/."$playlist");do
				grep -v "$u" playlists/$playlist	>		/tmp/$playlist.$$
				mv			  /tmp/$playlist.$$ playlists/$playlist
				echo -n "."
			done
			echo ""
			echo "Good:	Processed  Mute List."
		fi
	else
		echo "OK:	NonExistant Mute List."
	fi

#
#	PLAY STREAMS FROM INTERNET LISTED IN PLAYIST
#
	for f in $(cat playlists/$playlist);do
		echo "======= Begin: $f ======="
#		ping -c 1 `echo $f \
#			| sed 's/http:\/\///' \
#			| sed 's/\/.*$//' \
#			| sed 's/:.*$//'`
#		if [[ $? = 0 ]]
#		then
			exitval=$("$player" "$player_options" "$f")
			if [ $? == 0 ]
			then
				echo "========= End: $f ======="
				echo -n "Disposition: ('rm' to remove/mute)?: "
				read a
				if [ "$a" = "rm" ]
				then
					echo "$f" >> playlists/."$playlist"
					echo "MUTED:          $f"
				else
					echo "KEPT:           $f"
				fi
			else
				echo "$f" >> playlists/."$playlist"
				echo "FAILED:           $f"
			fi
#		else
#			echo "$f" >> playlists/."$playlist"
#			echo "OFFLINE:          $f"
#		fi
	done

#
#	ASK IF WE SHOULD REENABLE ALL KNOWN CHANNELS
#
        echo ======= END OF PLAYLIST, READY TO START OVER =======
        echo -n "Clear Mute List ('yes' to reenable all streams)?: "
        read a
        if [ "$a" = "yes" ]
        then
                mv      playlists/."$playlist"	playlists/."$playlist"-
		cat	playlists/"$playlist"	playlists/."$playlist"-	| sort -u >	playlists/."$playlist"
		mv	playlists/."$playlist"	playlists/"$playlist"
                echo "MUTE LIST CLEARED."
        else
                echo "MUTE LIST RETAINED."
        fi
        echo ======= 1 Infinite Loop =======

done
exitval=0
exit $exitval
# if the variable "file" contains a file's basename,
# we can substitute the existing extension to be ".ext" by:
# ${file%.*}.ext

# we want to ignore these files:
# CACHEDIR.TAG
# HEADER.html
# README.html
# index.html
