#!/bin/bash

#====================================================================================================
#  リストのダブルクリックで情報をコピー
#====================================================================================================

if [ "$1" == "--dclk" ] ; then
	info="【$3】$2"
	echo "${info}" | xsel -i -b &
	exit 0
fi


#====================================================================================================
#  下準備
#====================================================================================================

# キャッシュフォルダの設定
cachedir="${HOME}/.cache/bean_shoutcast"
if [ ! -d "${cachedir}" ] ; then
	mkdir -p "${cachedir}"
fi

# 音楽再生用のデフォルトアプリを探す
if [ $(ps alxww | grep pcmanfm | grep -v grep | wc -l) -gt 0 ] && [ -f "/home/user/.local/share/applications/mimeapps.list" ]; then
	desktop="$(cat /home/user/.local/share/applications/mimeapps.list | grep -m 1 audio/mpeg | cut -d= -f2 | cut -d\; -f1)"
elif which xdg-mime > /dev/null 2>&1 ; then
	desktop="$(xdg-mime query default audio/mpeg)"
else
	desktop=""
fi

# デフォルトアプリのコマンドを抽出する
if [ "${desktop}" == "" ] ; then
	if which gogglesmm > /dev/null 2>&1 ; then
		cmd=gogglesmm
	else
		cmd=x-www-browser
	fi
	
elif [ -f "${HOME}/.local/share/applications/${desktop}" ] ; then
	cmd=$(cat "${HOME}/.local/share/applications/${desktop}" | grep "^Exec=" | cut -d= -f2 | sed -e "s|%\S\+||igm" -e "s|^\s*||igm" -e "s|\s*$||igm")
	
elif [ -f "/usr/local/share/applications/${desktop}" ] ; then
	cmd=$(cat "/usr/local/share/applications/${desktop}" | grep "^Exec=" | cut -d= -f2 | sed -e "s|%\S\+||igm" -e "s|^\s*||igm" -e "s|\s*$||igm")
	
elif [ -f "/usr/share/applications/${desktop}" ] ; then
	cmd=$(cat "/usr/share/applications/${desktop}" | grep "^Exec=" | cut -d= -f2 | sed -e "s|%\S\+||igm" -e "s|^\s*||igm" -e "s|\s*$||igm")
	
else
	cmd=x-www-browser
fi


#====================================================================================================
#  メーター表示用の関数
#====================================================================================================

# ジャンル一覧の取得
_genres()
{
	echo 0
	
	wget -q http://www.shoutcast.com/ -O- | \
		grep href=       | \
		grep -v "</h4>"  | \
		grep -o "cat=.*" | \
		sed \
			-e "s|cat=\(.*\)</li>|    \1|igm" \
			-e "s|cat=||igm"                | \
		grep -o "^[^#]*" > "${cachedir}/genres.txt"
		
	#	sed \
	#		-e "s|^\(\S.\+\)|\1\n@#ff9999|igm" \
	#		-e "s|^\s\s\+\(\S.\+\)|\1\n@#f3f3f3|igm" \
	#		-e "s|^@||igm" \
}

# ラジオ局一覧の取得
_stations()
{
	local cat
	local str
	local act
	local url
	
	echo 0
	
	if [ "$1" == "--search" ] ; then
		cat=""
		str="$(echo $2 | nkf -wMQ | tr = %)"
		act="search"
	elif [ "$1" == "--genre" ] ; then
		cat="$(echo $2 | nkf -wMQ | tr = %)"
		str=""
		act="sub"
	else
		cat=""
		str=""
		act="none"
	fi
	
	url="http://www.shoutcast.com/radiolist.cfm?action=${act}&string=${str}&cat=${cat}&amount=10000&order=listeners&_cf_containerId=radiolist&_cf_nodebug=true&_cf_nocache=true&_cf_rc=0"
	
	wget -q "${url}" -O-  | \
		grep "<td" | \
		sed \
			-e "s|^.*\(http[^\"]*\).*<img.*$|\1|igm" \
			-e "s|^.*>\([^>]*\)</a></td>|\1|igm"     \
			-e "s|^.*>\([^<]\+\)<.*$|\1|igm"       | \
		tail -n +7 > "${cachedir}/stations.txt"
}


#====================================================================================================
#  処理開始
#====================================================================================================

while true ; do
	
	keyword=""
	genre=""
	station=""
	
	keyword=$(
		yad \
			--title="linuxBean ラジオチューナー" \
			--on-top --center --borders=10 --width=600 \
			--window-icon=radiotray --image=radiotray  \
			--text "  SHOUTcastに登録されているインターネットラジオ局を検索します。\n  空欄のままOKを押すと、代わりにジャンル選択画面を表示します。" \
			--form --field=""
	)
	if [ $? -gt 0 ] ; then
		exit 1
	fi
	keyword=$(echo "${keyword}" | cut -d\| -f1)
	
	if [ "${keyword}" == "" ] ; then
		
		if [ ! -f "${cachedir}/genres.txt" ] || [ $(expr $(date +%s) - $(stat -c %Y "${cachedir}/genres.txt")) -gt 604800 ] ; then
			_genres | \
				yad --title="接続中" --on-top --center \
				--window-icon=radiotray --image=radiotray \
				--text "ジャンルの一覧を取得しています..." --progress --pulsate --auto-close
		fi
		
		genre=$(
			cat "${cachedir}/genres.txt" | \
				yad \
					--title="ジャンル" \
					--on-top --center --width=200 --height=480 --window-icon=radiotray \
					--text="ジャンルを選んでください。\nキャンセルで検索画面に戻ります。" --list  \
					--column=Genre --search-column=1 | \
				cut -d\| -f1
			
				#	--column=Genre --column=@back@ --search-column=1 | \
		)
		
		if [ "${genre}" == "" ] ; then
			continue
		fi
		
		_stations --genre "${genre}" | \
			yad --title="接続中" --on-top --center \
			--window-icon=radiotray --image=radiotray \
			--text "ラジオ局の一覧を取得しています..." --progress --pulsate --auto-close

	else
		_stations --search "${keyword}" | \
			yad --title="検索中" --on-top --center \
			--window-icon=radiotray --image=radiotray \
			--text "ラジオ局の一覧を取得しています..." --progress --pulsate --auto-close
	fi
	
	while true ; do
		station=$(
			cat "${cachedir}/stations.txt" | \
				yad \
					--title="linuxBean ラジオチューナー" \
					--on-top --center --width=600 --height=400 --window-icon=radiotray \
					--text="聴取したいラジオ局を選んでください。OKで再生、キャンセルで検索画面に戻ります。\nまた、リストをダブルクリックすると、ラジオ局名と選局用URLをクリップボードにコピーします。" \
					--list --search-column=2 --hide-column=1 \
					--dclick-action="$0 --dclk %s" \
					--column="URL" --column="ラジオ局名" --column="ジャンル" --column="聴取者:NUM" --column="kbps:NUM" --column="形式"
		)
		if [ $? -gt 0 ] ; then
			break
		fi
		station=$(echo "${station}" | cut -d\| -f1)
		echo "${cmd} \"${station}\""
		
		if [ "${station}" == "" ] ; then
			break
		else
			nohup ${cmd} "${station}" > /dev/null 2>&1 &
		fi
		
		if which streamripper > /dev/null 2>&1 ; then
			yad \
				--title="streamripper" \
				--on-top --center --borders=10 \
				--window-icon=radiotray --image=radiotray  \
				--text " このラジオ局の放送を録音しますか？\n\n OK: 録音を開始して選曲画面に戻る\n キャンセル: 何もせず選曲画面に戻る"
		
			if [ $? -gt 0 ] ; then
				continue
			else
				cd "${HOME}" > /dev/null 2>&1
				nohup x-terminal-emulator -e streamripper ${station} > /dev/null 2>&1 &
				cd - > /dev/null 2>&1
				continue
			fi
		fi
	done
done
