#!/bin/bash
#                       /usr/local/bin/kkcr
# https://crystalfaeries.net/posix/bin/kkcr
# celeste@crystalfaeries.net 2021-04-26 06:09:28+00:00
# Port 8009 is Reserved for relaying local station KKCR/KAQA
# Accepts option:	"-n string_naming_the_recording"
# Accepts option:	duration_in_minutes
# Accepts both:		"-n string_naming_the_recording duration_in_minutes"
# else		record as long as user is monitoring the audio.
# Thus to record KKCR's monday+tuesday night 2 hours of jazz put in your .crontab:
# 00 18 * * 1,2	kkcr -n "kkcr_jazz" 120	# Assuming you are in HST timezone (UTC-10)
# such will run mplayer in the background with no interface, thus
# Accepts option "--kill"	to kill any streamrippers	(not just my own :-)
# Accepts option "-k"		to kill any mplayers		(not just my own :-)
# It is possible? to wind-up with an mplayer hard-looping in background? DEBUG clue!
# Accepts option "-t"		to name_tidy the /audio/streams directory tree
#				which will rename directories out from under any
#				running streamrippers, possibly resulting in abort
# This script will auto "-t" (tidy) upon completion of streamrip.
# With just the option "-p" we fetch the latest schedule of PROGRAMming
let help=20	# 1 less than the line number
let relay=8009	# Port Reserved for relaying local station KKCR/KAQA
ripdir="${HOME}/crystalfaeries.net/audio/streams/kkcr/"	# last character should be "/"
filename="$(now -f)"		# default file_name if not specified with -n
case $# in
0 )	# rip the stream ONLY as long as user listens...
	mkdir	   -p	"${ripdir}${filename}"		\
	&&	cd -P	"${ripdir}${filename}"		\
	&&	/usr/bin/streamripper	'https://s1.phx.icastcenter.com/tunein/kkcrssl.pls'	\
		-r ${relay} -R 0 --quiet &		# Rip in background while we
	let PID=$!			# save the PID
	mplayer -fs  -loop 255 http://localhost:${relay}	# Monitor the stream... until user "q"uits it
	for signal in hup term kill;do
		kill -"$signal" ${PID}			# kill the background streamripper
		sleep	10				# allowing a bit of clean-up time
	done	# fall through to rip_tidy (auto -t)
	;;
1 )	# hmmm... further parsing required
	case "${1}" in
	-v | --version )
		head -n 4 $0 | tail -n 1
		exit $?	# pau
		;;
	-h | --help )
		head -n $help $0
		exit $?	# pau
		;;
	-p | --program )	# fetch the latest program, display if changed
		mkdir -p	"${HOME}"/downloads/kkcr.org/docs/
		pushd		"${HOME}"/downloads/kkcr.org/docs/
		download		     http://kkcr.org/docs/KKCR_Program_Schedule.pdf
		sleep	60	# should be enuf unless very slow connection
		diff	kkcr_program_schedule.pdf		  KKCR_Program_Schedule.pdf
		let DIFF=$?
		name_tidy -r	# normalize
		case $DIFF in
		0)	echo "KKCR Programming UNchanged"
			;;
		*)	echo "KKCR Programming UPdated: $DIFF"
#			COMMENTED OUT BECAUSE THE RESULTS ARE USELESS (MicroShaft Xcel SpreadShit printed as PDF):
#			doc2html -i	`pwd`/kkcr_program_schedule.pdf
#			firefox		`pwd`/kkcr_program_schedule/*.htm{,l} < /dev/null >& /dev/null & disown %1
			okular		`pwd`/kkcr_program_schedule.pdf < /dev/null >& /dev/null & disown %1
			;;
		esac
		exit $?	# pau
		;;
	-k )	# NOTE: we indiscriminantly kill any mplayers we can find, not just our own in background from cron invocation
		for signal in hup term kill;do	# iterate forcefullness
		PIDS="$(ps -ef --forest | grep mplayer | grep -v grep | sed 's/    / /g;s/   / /g;s/  / /g;s/ /	/g' | cut -f2)"
#		echo	kill -"$signal" ${PIDS}			# kill mplayers - debugging version
#			kill -"$signal" ${PIDS}			# kill mplayers - debugging version
			kill -"$signal" ${PIDS}	2>/dev/null	# kill mplayers - pretty version
			sleep	10				# allowing a bit of clean-up time
		done
		exit $?	# pau - streamrips may continue even without our monitoring
		;;
	--kill )	# NOTE: we indiscriminantly kill any streamrips we can find, not just our own in background from cron invocation
		kkcr -k	&					# kill mplayers in the background while we...
		for signal in hup term kill;do	# iterate forcefullness
		PIDS="$(ps -ef --forest | grep streamripper | grep -v grep | sed 's/    / /g;s/   / /g;s/  / /g;s/ /	/g' | cut -f2)"
#		echo	kill -"$signal" ${PIDS}			# kill streamrippers - debugging version
#			kill -"$signal" ${PIDS}			# kill streamrippers - debugging version
			kill -"$signal" ${PIDS}	2>/dev/null	# kill streamrippers - pretty version
			sleep	10				# allowing a bit of clean-up time
		done	# fall through to rip_tidy now we're certain we won't undermine a running streamrip
		;;
	-t | --tidy )	# tidy the directory/file hierarchy
		name_tidy -r		"${HOME}"/crystalfaeries.net/audio/streams/
#		for directory in	"${HOME}"/crystalfaeries.net/audio/streams/*
#		do
#			name_tidy -r	"${directory}"
#		done
		for incomplete in $(find "${HOME}"/crystalfaeries.net/audio/streams/ -name incomplete -type d \! -size 0); do
		pushd $incomplete || exit 255	# what, a permissions problem?
			mv -i * ..
			rm -rf `pwd`
			cd -P ..
			for f in *
			do	# get dem spaces outta da file names, nor begin with a -
				mv -i "${f}" ../"`pwd`"."$(echo "${f}"|sed 's/  / /;s/ - /-/;s/^-//')"
			done
			rmdir	`pwd`
		popd
		done
		exit	$?	# pau tidy
		;;
	* )	# only one argument must be duration in minutes
		mkdir	   -p	"${HOME}"/crystalfaeries.net/audio/streams/"${filename}"		\
		&&	cd -P	"${HOME}"/crystalfaeries.net/audio/streams/"${filename}"		\
		&&	/usr/bin/streamripper	'https://s1.phx.icastcenter.com/tunein/kkcrssl.pls'	\
			-r ${relay} -R 0 --quiet	-l $(echo "60*${1}" | bc)	&	# Rip in background
		let PID=$!					# save the PID
		echo	"streamripping as PID ${PID} for ${1} minutes..."
		mplayer -fs -loop 255 http://localhost:${relay}	# Monitor the stream...
		echo	"streamripping as PID ${PID}..."
		exit $?	# pau - streamrips may continue even without our monitoring
		;;
	esac
	;;
2 )	# hmmm... should be "-n file_name" with no duration specified
	if [ "${1}" == "-n" ]
	then	# yep, we gonna skip some error checking we COULD do here :-)
		mkdir	   -p	"${ripdir}${2}"			\
		&&	cd -P	"${ripdir}${2}"			\
		&&	/usr/bin/streamripper	'https://s1.phx.icastcenter.com/tunein/kkcrssl.pls'	\
			-r ${relay} -R 0 --quiet &		# Rip in background while we
		let PID=$!			# save the PID
		mplayer -fs  -loop 255 http://localhost:${relay}	# Monitor the stream...
		for signal in hup term kill;do
			kill -"$signal" ${PID}			# kill the background streamripper
			sleep	10				# allowing a bit of clean-up time
		done	# fall through to rip_tidy
	else
		echo "$0: unknown option(s) ${@}"	1>&2
		exec	"${0}" --help	# help the user
	fi	# fall through to auto-tidy
	;;
* )	# hmmm... should be "-n file_name duration", but, we gonna skip some error checking we COULD do here :-)
	if [ "${1}" == "-n" ]
	then
		mkdir	   -p	"${ripdir}${2}"			\
		&&	cd -P	"${ripdir}${2}"			\
		&&	/usr/bin/streamripper	'https://s1.phx.icastcenter.com/tunein/kkcrssl.pls'	\
			-r ${relay} -R 0 --quiet	-l $(echo "60*${3}" | bc)	&	# Rip in background
		let PID=$!					# save the PID
		mplayer -fs  -loop 255 http://localhost:${relay}	# Monitor the stream...
		exit	$?	# pau monitoring, streamrip continues in background...
	else
		echo "$0: unknown option(s) ${@}"	1>&2
		exec	"${0}" --help	# help the user
	fi
	;;
esac
exec	kkcr	-t	# tidy up our streamrips
exit	255		# you can't be here: execs don't return!

# While a cron-launched rip+monitor was running in background,
# could we successfully kill the no-interfaced mplayer
# and then resume MONITORing with our monitor script,
# so that upon conclusion of the program, we auto continue
# with our playlist... and, yes, it succeeded,
# with expected 45 second delay in the kill loop.
celeste@fey:~$ kkcr -k;monitor
MPlayer 1.3.0 (Debian), built with gcc-10 (C) 2000-2016 MPlayer Team
do_connect: could not connect to socket
connect: No such file or directory

Playing http://127.0.0.1:8009.
Resolving 127.0.0.1 for AF_INET6...

Couldn't resolve name for AF_INET6: 127.0.0.1
Connecting to server 127.0.0.1[127.0.0.1]: 8009...

Name   : KKCR Kaua'i Community Radio
Website: www.kkcr.org
Bitrate: 128kbit/s
Cache size set to 320 KBytes
Cache fill: 15.00% (49152 bytes)   

Audio only file format detected.
==========================================================================
Opening audio decoder: [mpg123] MPEG 1.0/2.0/2.5 layers I, II, III
AUDIO: 44100 Hz, 2 ch, s16le, 128.0 kbit/9.07% (ratio: 16000->176400)
Selected audio codec: [mpg123] afm: mpg123 (MPEG 1.0/2.0/2.5 layers I, II, III)
==========================================================================
AO: [pulse] 44100Hz 2ch s16le (2 bytes per sample)
Video: no video

A:  17.1 (17.1) of -0.0 (unknown)  0.7% 18% 

----------------------------------------------------------------------------
celeste@fey:~$ kkcr --kill
renamed "./KKCR Kaua'i Community Radio" -> 'kkcr_kaua_i_community_radio'
~/crystalfaeries.net/audio/streams/kkcr/kauai_live/kkcr_kaua_i_community_radio/incomplete ~
mv: cannot move '2020-09-21.03-21.mp3' to '..//home/celeste/crystalfaeries.net/audio/streams/kkcr/kauai_live/kkcr_kaua_i_community_radio.2020-09-21.03-21.mp3': No such file or directory
rmdir: failed to remove '/home/celeste/crystalfaeries.net/audio/streams/kkcr/kauai_live/kkcr_kaua_i_community_radio': Directory not empty
~

