#!/bin/bash -e
# Ario(mpdクライアント)のインターネットラジオ・ライブラリに
# SHOUTcast等のplsファイルから取得したURLを追加する。
#
[ $# -lt 1 ] && echo "$0 playlist" && exit 1
title="`grep Title "${1}"|cut -d")" -f2-|cut -b2-|head -1`"

title=$(echo "${title}"|sed -e 's/&/&amp;/'g)
title=$(echo "${title}"|sed -e 's/>/&gt;/'g)
title=$(echo "${title}"|sed -e 's/</&lt;/'g)
title=$(echo "${title}"|sed -e 's/à/&#xE0;/'g)
title=$(echo "${title}"|sed -e 's/ì/&#xEC;/'g)
title=$(echo "${title}"|sed -e 's/ù/&#xF9;/'g)
title=$(echo "${title}"|sed -e 's/è/&#xE8;/'g)
title=$(echo "${title}"|sed -e 's/ò/&#xF2;/'g)
title=$(echo "${title}"|sed -e 's/ä/&#xE4;/'g)
title=$(echo "${title}"|sed -e 's/ï/&#xEF;/'g)
title=$(echo "${title}"|sed -e 's/ü/&#xFC;/'g)
title=$(echo "${title}"|sed -e 's/ë/&#xEB;/'g)
title=$(echo "${title}"|sed -e 's/ö/&#xF6;/'g)
title=$(echo "${title}"|sed -e 's/€/&#x20AC;/'g)

url="`grep http "${1}"|head -1|cut -d"=" -f2`"

WEBRADIOXML=$(echo ~/.config/ario/radios/radios.xml)
WEBRADIODIR=${WEBRADIOXML%/*}  # 最後の/より前の文字列を取り出す
if !(test -e ${WEBRADIOXML}) then
mkdir -p ${WEBRADIODIR}
cp -p /usr/share/ario/plugins/radios.xml.default ${WEBRADIOXML}
fi

unset TEMPFILE

exitproc()
{
rm -rf ${TEMPFILE}
}

trap '
exitproc
exit 1
' 2 15
TEMPFILE=$(mktemp)


echo "<?xml version=\"1.0\" standalone=\"no\"?>" >> ${TEMPFILE}
echo "<ario-radios>"                             >> ${TEMPFILE}

grep "<radio url=" ${WEBRADIOXML}|while read -r i
do
echo "  ${i}"             >> ${TEMPFILE}
done

echo -n "  <radio url=\"" >> ${TEMPFILE}
echo -n "${url}"          >> ${TEMPFILE}
echo -n "\">"             >> ${TEMPFILE}
echo -n "${title}"        >> ${TEMPFILE}
echo    "</radio>"        >> ${TEMPFILE}

echo  "</ario-radios>"    >> ${TEMPFILE}

cat ${TEMPFILE} > ${WEBRADIOXML}
exitproc
