#!/bin/bash -

# Linux bash invoked as sh lacks of $RANDOM

#exec > /tmp/log 2>&1
#set -x
#
# (c) Wed 21 May 2025 08:42:24 PM CEST
# Version: 0.4.0
#
# CGI for browsing/streaming/searching MP3 collections
#
# Requires:
#	POSIX bourne shell (sh, bash, ksh)
#	perl
#	recode
#   charconv : http://www.chemie.fu-berlin.de/chemnet/use/charconv.html
#	zip : http://www.info-zip.org/
#	mp3info: http://www.ibiblio.org/mp3info/
#	id3v2
#	jhead
#	dewplayer: http://www.alsacreations.fr/dewplayer.html
#   HTML5 Player: https://codepen.io/craigstroman/pen/aOyRYx
#	convert (ImageMagick)
#	
#
set -f
#ulimit -f 0
# Uncomment these if your /bin/sh understand them.
ulimit -c 0
#ulimit -d 8192
ulimit -t 60
#ulimit -v 8192
#ulimit -m 8192

#
# Variables you have to customize
# (put them on /usr/local/etc/stream.conf )
#

VERSION="0.4.0"


id3v2=/usr/bin/id3v2
if test -x $id3v2
then
	:
else
	id3v2=/usr/local/bin/id3v2
fi

. /usr/local/etc/stream.conf

# IDX: This directory has:
# 	list-*txt file with relative paths to all albums
#	songs.txt relative path of every song

#### IDX=/raid/media/music/index/


# ROOT: Your music store
#
#	Music sould be stored there as:
# 	Initial/Artist/year-album/track-title.mp3
#	Example: D/Dead Can Dance/1990-Aion/04-The Song of the Sybil.mp3
#	

#### ROOT=/raid/media/music

# XMLCACHE: where XML playlists are stored.

#### XMLCACHE=/raid/www/music/tmp/
#### XMLCACHEURI=/music/tmp/

# OWNER: POSIX owner of files for filtered listings
#### OWNER=spd

# URL of this script, without host part
#### MYNAME=/cgi/stream

# Main page
#### MAIN=/music/

# Where is dewplayer
#### PLAYERDIR=/music/player/
#### DEWPLAYER=${PLAYERDIR}dewplayer-playlist.swf

####
#
# End of customizable options
#
####

PATH=$PATH:/usr/local/bin
LANG=C; export LANG
LANGUAGE=C; export LANGUAGE
LC_ALL=C; export LC_ALL

error=:
errormsg=""


# URL decoding
htd()
{
	perl -pe 's/\%([A-Fa-f0-9]{2})/pack("C", hex($1))/seg;'
}

# trim unwanted (dangerous) characters
sanitize()
{
	tr -c -d "0-9,a-z,A-Z, +=:.!?/\-()'\[\]" | sed -e 's,//*,/,g' |\
	sed -e 's,/\.[\.]*,/.,g' -e 's,\/\.\/,/,g' -e 's,^\.[\.]*,/,g'
}

# URL encoding for spaces (we are using ASCII-7 for file names)
hte()
{
	sed -e 's/ /%20/g'
}

htmlheader()
{
	echo "Server: Apache"
	echo "Content-type: text/html; charset=ISO-8859-1"
	echo
}

htmlhead()
{
	cat <<-EOF
		<!DOCTYPE html>
		<head>
		<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
		<meta name="author" content="stream (aTunes)">
		<link rel='stylesheet' href='//maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css'>
		<link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.3.0/css/font-awesome.min.css'>
		<link rel="stylesheet" href="${PLAYERDIR}/player.css">
		<title>
		$1
		</title>
	EOF
	css

	echo "</head>"
}
htmltitle()
{
	echo "<table border='0' class='zebra'><tbody>"
	echo "<tr class='even'>"
	echo "<td>"
	echo "<h1 class="h1navbar">$*</h1>"
	#echo $*
	echo "</td>"
	echo "</tr>"
	echo "</tbody></table>"


	LINK=""

	if $GUI_FAST
	then
		LINK="${MSGFAST}-"
	else
		LINK="<A HREF=\"${MYNAME}?${VFUL}${QUERY_STRING}\">${MSGFAST}</A>-"
	fi
	if $GUI_DETAIL
	then
		LINK=${LINK}"${MSGDETAIL}-"
	else
		LINK=${LINK}"<A HREF=\"${MYNAME}?${VFUL}detail=true&${QUERY_STRING}\">${MSGDETAIL}</A>-"
	fi
	if $GUI_MINI
	then
		LINK=${LINK}"${MSGMINI}"
	else
		LINK=${LINK}"<A HREF=\"${MYNAME}?${VFUL}detail=mini&${QUERY_STRING}\">${MSGMINI}</A>"
	fi

	if $FULL
	then
		LINK2="<A HREF=\"${MYNAME}?${VDET}${QUERY_STRING}\">${MSGFILTER}</A>-${MSGALL}"
	else
		LINK2="${MSGFILTER}-<A HREF=\"${MYNAME}?full=true&amp;${VDET}$QUERY_STRING\">${MSGALL}</A>"
	fi

	echo "<h2 class=\"h2title\">${MSGVIEW}:&nbsp;&nbsp;&nbsp; $LINK | $LINK2</h2>"
	echo "<br><br>"

}

css()
{
	cat <<-EOF
<style type="text/css">
table.zebra {
	border-width: 0px;
	border-spacing: ;
	border-style: none;
	border-color: gray;
	border-collapse: collapse;
	background-color: white;
}
table.zebra th {
	border-width: 1px;
	padding: 2px;
	border-style: inset;
	border-color: gray;
	background-color: white;
	-moz-border-radius: ;
}
table.zebra td {
	border-width: 1px;
	padding: 2px;
	border-style: inset;
	border-color: gray;
	background-color: white;
	-moz-border-radius: ;
}
table.zebra tr.even td {
	background-color: #ddf;
}
table.zebra tr.odd td {
	background-color: #fff;
}

.h1navbar {
	font-family:verdana, geneva, lucida, 'lucida grande', arial, helvetica, sans-serif;
	margin:5;
	font-size: 16pt;
	font-weight: bold;
	display: inline;
}
.h2title {
	font-family:verdana, geneva, lucida, 'lucida grande', arial, helvetica, sans-serif;
	margin:5;
	font-size: 12pt;
	font-weight: bold;
	display: inline;
}


</style>

	EOF
}

m3uheader()
{
	echo "Server: Apache"
	echo "Content-type: audio/x-mpegurl"
	echo "Content-Disposition: attachment; filename=\"$1\""
	echo
}

zipheader()
{
	echo "Server: Apache"
	echo "Content-type: application/zip"
	echo "Content-Disposition: attachment; filename=\"$1\""
	echo
}


if [ "_${REMOTE_USER}" = "_" ]
then
	htmlheader
	htmlhead "Not allowed"

	cat <<EOF
	<body>
	<h1>Not allowed</h1>
	<p>Please, login first.</p>
	<hr>
	</body></html>
EOF
	exit 0
fi

case "_${HTTP_ACCEPT_LANGUAGE}" in

	_es*)
	MSGVIEW="Vista"
	MSGFAST="Rpido"
	MSGDETAIL="Detallado"
	MSGMINI="Mini"
	MSGFILTER="Filtrado"
	MSGALL="Todo"
	MSGSEARCHR="Buscar Disco"
	MSGSEARCHS="Buscar Cancin"
	MSGSBYDATE="Por Fecha"
	MSGSRANDOM="Aleatorio"
	MSGSTATS="Estadsticas"
	MSGDOWNLOAD="Descargar Disco"
	MSGRESULTS="Resultados para"
	MSGRANDOMPL="Lista aleatoria"
	MSGSONGS="canciones"
	;;

	*)
	MSGVIEW="View"
	MSGFAST="Fast"
	MSGDETAIL="Detail"
	MSGMINI="Mini"
	MSGFILTER="Filtered"
	MSGALL="All"
	MSGSEARCHR="Search album"
	MSGSEARCHS="Search song"
	MSGSBYDATE="By date"
	MSGSRANDOM="Random"
	MSGSTATS="Stats"
	MSGDOWNLOAD="Download album"
	MSGRESULTS="Results for"
	MSGRANDOMPL="Random playlist"
	MSGSONGS="songs"
	;;
esac

if [ "_${QUERY_STRING}_" = "__" ]
then
        read QUERY_STRING
        REQUEST_METHOD=GET
        export REQUEST_METHOD
        export QUERY_STRING
fi

htmlfooter()
{
		HF=""
		if $FULL
		then
			HF='<INPUT TYPE="hidden" NAME="full" VALUE="true">'
		fi
		if [ "_$DVALUE" != "_" ]
		then
			HF=${HF}'<INPUT TYPE="hidden" NAME="detail" VALUE="'${DVALUE}'">'
		fi
		cat <<-EOF
		<HR>
		<TABLE>
		<TR>
			<TD>
			<FORM ACTION="$MYNAME" METHOD="GET">
			$HF
			<INPUT TYPE="text" NAME="search">
			<INPUT TYPE="submit" VALUE="${MSGSEARCHR}">
			</FORM>
			</TD>
			<TD ALIGN="CENTER">-</TD>
			<TD>
			<FORM ACTION="$MYNAME" METHOD="GET">
			$HF
			<INPUT TYPE="text" WIDTH="4" NAME="random">
			<INPUT TYPE="submit" VALUE="${MSGSRANDOM}"></FORM>
			</TD>
		</TR><TR>
			<TD>
			<FORM ACTION="$MYNAME" METHOD="GET">
			$HF
			<INPUT TYPE="text" NAME="song">
			<INPUT TYPE="submit" VALUE="${MSGSEARCHS}">
			</FORM>
			</TD>
		EOF
		
		if [ "_$WHAT" != "_"  ]
		then
			:
		else
		if test -f $FRONT || ls -1 | egrep "^01.*mp3$" >/dev/null 2>&1
		then
				cat <<EOF
		<TD ALIGN="CENTER">-</TD>
		<TD><FORM ACTION="$MYNAME" METHOD="GET"><INPUT TYPE="hidden" NAME="zip" VALUE="`echo "$file"`"><INPUT TYPE="submit" VALUE="${MSGDOWNLOAD}"></FORM></TD>
EOF
		fi
		fi
		cat << EOF
		</TR>
		</TABLE>
		<P>
		<FONT SIZE="-5">
		<a href="${MAIN}music.xml"><IMG SRC="${MAIN}feed-icon-14x14.png" ALT="atom"></a>
		&nbsp;
		<a href="${MAIN}index-by-date.html">${MSGSBYDATE}</a>
		&nbsp;
		<a href="/musica/">${MSGALL}</a>
		&nbsp;&nbsp;
		<a href="$MYNAME">/</a>
		&nbsp;&nbsp;
		<a href="$MAIN">${MSGSTATS}</a>
		&nbsp;&nbsp;
		&nbsp;&nbsp;
		<a href="http://webdiis.unizar.es/~spd/spdsoft.html">&copy SPDsoft 2011-2025</a>
		&nbsp;&nbsp;
		&nbsp;&nbsp;
		<a href="http://webdiis.unizar.es/~spd/stream/">
		Stream Version $VERSION
		&nbsp;&nbsp;
		<img src="${PLAYERDIR}/tuna_s.png"></a>
		</FONT>
		<HR>
		</body>
		</html>
EOF

}

xmlentry()
{
	FILE="$1"
	uri="$2"
	dir="$3"
	uri=`echo "$uri" | sed -e 's,^[/]*,/,'`

	OLANG="$LANG"
	LANG=en_US.iso88591; export LANG
	unset LC_ALL
	unset LANGUAGE
	# otherwise id3v2 won't display latin-1 characters

	XMLTITLE=`$id3v2 -l "$FILE" | sed -ne '/^TIT2/s/.*): //p'`
	if [ "_$XMLTITLE" = "_" ]
	then
		XMLTITLE=`mp3info -p %t "$FILE"`
	fi
	XMLARTIST=`$id3v2 -l "$FILE" | sed -ne '/^TPE1/s/.*): //p'`
	if [ "_$XMLARTIST" = "_" ]
	then
		XMLARTIST=`mp3info -p %a "$FILE"`
	fi
	XMLALBUM=`$id3v2 -l "$FILE" | sed -ne '/^TALB/s/.*): //p'`
	if [ "_$XMLALBUM" = "_" ]
	then
		XMLALBUM=`mp3info -p %l "$FILE"`
	fi

	if [ $XMLTRACK = "0" ]
	then
		html51head
		html52head
		XMLTRACK=1
	fi

	XMLTITLE=`echo "${XMLTITLE}" | sed -e 's/&/&amp;/g'`
	XMLARTIST=`echo "${XMLARTIST}" | sed -e 's/&/&amp;/g'`
	XMLALBUM=`echo "${XMLALBUM}" | sed -e 's/&/&amp;/g'`
	XMLTITLEU=`echo "${XMLTITLE}" | recode latin1..utf8`
	XMLARTISTU=`echo "${XMLARTIST}" | recode latin1..utf8`
	XMLALBUMU=`echo "${XMLALBUM}" | recode latin1..utf8`

	XMLLENGTH=`mp3info -p %S "$FILE"`


	echo "        <track>" >> "${XML}"
	echo "            <location>/musica$uri</location>" >> "${XML}"
	echo "            <creator>$XMLARTISTU</creator>" >> "${XML}"
	echo "            <album>$XMLALBUMU</album>" >> "${XML}"
	echo "            <title>$XMLTITLEU</title>" >> "${XML}"
	echo "            <duration>${XMLLENGTH}000</duration>" >> "${XML}"
	echo "            <image>front.jpg</image>" >> "${XML}"
	echo "        </track>" >> "${XML}"
	echo "" >> "${XML}"

	echo "   <source src=\"/musica$dir/$FILE\" data-track-number=\"${XMLTRACK}\"/>" >> "${HTML51}"

	cat << EOF >> "${HTML52}"
<div class="play-list-row" data-track-row="${XMLTRACK}">
   <div class="small-toggle-btn">
      <i class="small-play-btn"><span class="screen-reader-text">Small toggle button</span></i>
   </div>
  <div class="track-number">
   ${XMLTRACK}.
  </div>
  <div class="track-title">
    <a class="playlist-track" href="#" data-play-track="${XMLTRACK}">${XMLTITLE}</a>
  </div>
</div>
EOF

	LANG="$OLANG"
	LC_ALL=C
	LANGUAGE=C
}


html51head()
{
echo "<div class=\"container\">" > "${HTML51}"
echo "  <audio id=\"audio\" preload=\"none\" tabindex=\"0\">" >> "${HTML51}"
}
html51tail()
{
cat << EOF >> "${HTML51}"
    <object type="application/x-shockwave-flash" data="$DEWPLAYER" width="240" height="200" id="dewplayer" name="dewplayer">
      <param name="wmode" value="transparent" />
      <param name="movie" value="$DEWPLAYER" />
      <param name="flashvars" value="volume=100&showtime=true&autoreplay=true&xml=${XMLCACHEURI}/${XMLFILE}" />
    </object>
  </audio>
EOF
}

html52head()
{
	cat << EOF > "${HTML52}"
  <div class="player">

    <div class="large-toggle-btn">
      <i class="large-play-btn"><span class="screen-reader-text">Large toggle button</span></i>
    </div>
    <!-- /.play-box -->

    <div class="info-box">
      <div class="track-info-box">
        <div class="track-title-text"></div>
        <div class="audio-time">
          <span class="current-time">00:00</span> /
          <span class="duration">00:00</span>
        </div>
      </div>
      <!-- /.info-box -->

      <div class="progress-box">
        <div class="progress-cell">
          <div class="progress">
            <div class="progress-buffer"></div>
            <div class="progress-indicator"></div>
          </div>
        </div>
      </div>

    </div>
    <!-- /.progress-box -->

    <div class="controls-box">
      <i class="previous-track-btn disabled"><span class="screen-reader-text">Previous track button</span></i>
      <i class="next-track-btn"><span class="screen-reader-text">Next track button</span></i>
    </div>
    <!-- /.controls-box -->

  </div>
  <!-- /.player -->

  <div class="play-list">

EOF
}
html52tail()
{
	cat << EOF >> "${HTML52}"
    </div>
    </div>
	<script  src="${PLAYERDIR}/player.js"></script>
EOF
}

###########################################################################
#
# Generate zip file from record
#

if expr "_$QUERY_STRING" : "^_zip=..*" >/dev/null 2>&1
then
	file=`echo "$QUERY_STRING" | sed -e "s/^zip=//"  -e 's/&.*//' | htd | tr '+' ' ' | sanitize `
	
	cd "$ROOT"/"$file"

	if test -f front.jpg || test -f ../front.jpg ||\
		ls -1 | egrep "^01.*mp3$" >/dev/null 2>&1
	then
		# Is a music directory

		zipheader `echo "$file" | sed -e 's,/,_,g' -e 's/ //g'`.zip
		set +f
		DIR=`basename "$PWD"`
		cd ..
		zip -r0 - "$DIR"
		exit 0

	else
		error=:
		errormsg="Not a valid music directory"
	fi
fi

###########################################################################
#
# Create m3u
#

if expr "_$QUERY_STRING" : "^_stream=..*" >/dev/null 2>&1
then
	file=`echo "$QUERY_STRING" | sed -e "s/^stream=//"  -e 's/&.*//' | htd | tr '+' ' ' | sanitize `
	REMOTE_PASSWORD=`echo "$QUERY_STRING" | sed -e "s/.*&p=//" -e 's/&OK.*//' | htd`
	

	set -e
	cd "$ROOT"/"$file"

	m3uheader `echo "$file" | sed -e 's,/,_,g' -e 's/ //g'`.m3u
	echo "#EXTM3U"
	set +f
	for f in *mp3
	do
		set +e
		mp3info -p "#EXTINF: %S,%t\n" "$f" 2>/dev/null
		set -e
		echo "http://$REMOTE_USER:$REMOTE_PASSWORD@$SERVER_NAME/musica/$file/$f" | hte
	done
	exit 0
fi


###########################################################################
#
# Get "full" and "detail" status
#

OPTS=""
FULL=false
if expr "_$QUERY_STRING" : "^_full=true&" >/dev/null 2>&1
then
	FULL=:
	QUERY_STRING=`echo "$QUERY_STRING" | sed -e "s/^full=true&//"`
	VFUL="full=true&amp;"
else
	file=`echo "$QUERY_STRING" | htd | sanitize`
	VFUL=""
fi

GUI_DETAIL=false
GUI_INFO=false
GUI_PLAYER=false
GUI_M3U=:
GUI_FILES=:
GUI_MINI=false
GUI_FAST=:

DETAIL=false
if expr "_$QUERY_STRING" : "^_detail=.*&" >/dev/null 2>&1
then
	DVALUE=`echo "$QUERY_STRING" | sed -e "s/^detail=//" -e "s/&.*//"`
	QUERY_STRING=`echo "$QUERY_STRING" | sed -e "s/^detail=[a-z]*&//"`
	file=`echo "$QUERY_STRING" | htd | sanitize`
	VDET="detail=${DVALUE}&"
	case $DVALUE in
		true)
			GUI_DETAIL=:
			GUI_FAST=false
			GUI_INFO=:
			GUI_PLAYER=:
			GUI_M3U=false
			GUI_FILES=:
			;;
		mini)
			GUI_MINI=:
			GUI_FAST=false
			GUI_DETAIL=false
			GUI_INFO=false
			GUI_PLAYER=:
			GUI_M3U=false
			GUI_FILES=false
			;;
		*)
			GUI_FAST=:
			GUI_DETAIL=false
			GUI_INFO=false
			GUI_PLAYER=false
			GUI_M3U=:
			GUI_FILES=:
			;;

	esac
else
	file=`echo "$QUERY_STRING" | htd | sanitize`
	VDET=""
fi
OPTS="${VFUL}${VDET}"
fileuri=`echo "$file" | hte`


###########################################################################
#
# random playlist
#
if expr "_$QUERY_STRING" : "^_random=.*" >/dev/null 2>&1
then
	WHAT=`echo "$QUERY_STRING" | sed -e "s/^random=//"  -e 's/&.*//' | htd | charconv -fl -ta | tr '[A-Z]' '[a-z]' | tr '+' ' ' | sanitize`

	if expr "${WHAT}" : "[0-9][0-9]*" > /dev/null 2>&1
	then
		if [ $WHAT -gt 32 ]
		then
			WHAT=32
		else 
			if [ $WHAT -lt 1 ]
			then
				WHAT=1
			fi
		fi
	else
		WHAT=15
	fi
	htmlheader
	htmlhead "${MSGRANDOMPL} (\"$WHAT\" ${MSGSONGS})"

	echo "<body>"
	htmltitle "${MSGRANDOMPL} ($WHAT ${MSGSONGS})"
	IFS=:

	RANDOM=`(date; ls -altr /tmp ) | sum | tr -d -c '[0-9]'`
	IDXFILE="${IDX}"/songs.txt
	WC=`wc -l < $IDX/songs.txt | tr -d ' '`
	N=`expr $WC / 32767 + 1`
	if :
	then
			XMLFILE=playlist.$$.xml
			XMLDIR="${XMLCACHE}"
			XML="${XMLDIR}"/"${XMLFILE}"
			HTML51="${XMLDIR}/audio.html"
			HTML52="${XMLDIR}/player.html"
			PL=Random

			cat > "${XML}" <<EOF
<?xml version="1.0" encoding="UTF-8"?>
<playlist version="1" xmlns="http://xspf.org/ns/0/">
    <title>$PL</title>
    <creator>$MYNAME</creator>
    <image>front.jpg</image>

    <trackList>

EOF

		cd "$ROOT"
		echo "<UL>"
		i=0
		XMLTRACK=0
		while [ $i -lt $WHAT ]
		do
			n=`expr $RANDOM % $N + 1`
			L=`expr $RANDOM \* $n % $WC`
			i=`expr $i + 1`
			F=`tail -n +$L $IDX/songs.txt | head -1`
			uri=`echo "$F" | hte`
			xmlentry "$F" "/$uri" ""
			XMLTRACK=`expr $XMLTRACK + 1`
			echo "<li><a href=\"/musica/$uri\">$F</a>"
		done
		echo "</UL><HR>"

			cat >> "${XML}" <<EOF
    </trackList>
</playlist>
EOF
		echo "<TABLE><tr><td>"
		html51tail
        cat "${HTML51}"

        html52tail
        cat "${HTML52}"

		echo "</tr></td></TABLE>"

		echo "<HR><P>"

	else
		echo "<UL>"
		i=0
		while [ $i -lt $WHAT ]
		do
			n=`expr $RANDOM % $N + 1`
			L=`expr $RANDOM \* $n % $WC`
			i=`expr $i + 1`
			echo "<li>"
			tail -n +$L $IDX/songs.txt | head -1
		done
		echo "</UL>"
	fi


	htmlfooter
	if [ -f "${XML}"]
	then
		rm "${XML}"
	fi
	exit 0
fi

###########################################################################
#
# Find album/artist
#

if expr "_$QUERY_STRING" : "^_search=..*" >/dev/null 2>&1
then
	WHAT=`echo "$QUERY_STRING" | sed -e "s/^search=//"  -e 's/&.*//' | htd | charconv -fl -ta | tr '[A-Z]' '[a-z]' | tr '+' ' ' | sanitize`
	htmlheader
	htmlhead "${MSGRESULTS} \"$WHAT\""

	echo "<body>"
	htmltitle "${MSGRESULTS} \"$WHAT\""
	echo "<UL>"
	IFS=:

	IDXFILE="${IDX}"/`cd "$IDX"; ls -1 | grep list- | tail -1`
		
	egrep -i "${WHAT}" "$IDXFILE" | while read line
	do
		uri=`echo "$line" | hte`
		echo "<li><a href=\"$MYNAME?$OPTS$uri\">$line</a>"
	done
	echo "</UL>"

	htmlfooter
	exit 0
fi

###########################################################################
#
# Find song
#

if expr "_$QUERY_STRING" : "^_song=..*" >/dev/null 2>&1
then
	WHAT=`echo "$QUERY_STRING" | sed -e "s/^song=//"  -e 's/&.*//' | htd | charconv -fl -ta | tr '[A-Z]' '[a-z]' | tr '+' ' ' | sanitize`
	htmlheader
	htmlhead "${MSGRESULTS} \"$WHAT\""

	echo "<body>"
	htmltitle "${MSGRESULTS} \"$WHAT\""
	echo "<UL>"
	IFS=:

	IDXFILE="${IDX}"/songs.txt
		
	egrep -i -e ".*/[^/]*${WHAT}[^/]*$" "$IDXFILE" | while read line
	do
		uri="$line"
		urid=`echo "$uri" | sed -e 's,\(.*\)/\([^/]*\),\1,'`
		urif=`echo "$uri" | sed -e 's,\(.*\)/\([^/]*\),\2,'`
		uridh=`echo "$urid" | hte`
		urifh=`echo "$urif" | hte`
		echo "<li><a href=\"$MYNAME?$OPTS/$uridh\">$urid</a>/<a href=\"/musica/$uridh/$urifh\">$urif</a>"
	done

	echo "</UL>"

	htmlfooter

	exit 0
fi

###########################################################################
#
# List directory
#

if [ "_$file" = "_" ]
then
	file=.
fi

if [ -d "$ROOT"/"$file" ]
then
	set +f
	error=false
	TITLE="$file"
		
	htmlheader
	htmlhead "$TITLE"
	cat << EOF
	<body>
EOF

	TITLEHTE=`echo "$TITLE" | hte`
	RECORD=`
	uri=;  sep=;
	echo "<a href=\"$MYNAME?$OPTS/\">/</A>"
	echo "$TITLEHTE" | tr / \\\\012 | grep . | while read line
	do
		uri=$uri$sep$line
		sep=/
		echo "<a href=\"$MYNAME?$OPTS/$uri\">"
		echo $line$sep | sed -e 's/%20/ /g'
		echo "</a>"
	done
	`
	htmltitle "$RECORD"

	cat << EOF
	<BR>
	<TABLE BORDER="0">
	<TR>
EOF
		set -e
		cd "$ROOT"/"$file"
		if [ "$file" = "." ]
		then
			file=""
		fi
		set +f
		FRONT=none
		if [ -f front.jpg ]
		then
			FRONT=front.jpg
		else
			if [ -f ../front.jpg ]
			then
				FRONT=../front.jpg
			fi
		fi

		if [ "$FRONT" != "none" ]
		then
			echo "<TD>"
			XMLDIR="${XMLCACHE}${file}"
			test -d "${XMLDIR}" || mkdir -p "${XMLDIR}"
			FRONTC="${XMLDIR}"/front.jpg

			if [ -f "$FRONTC" ]
			then
				:
			else
				convert  -resize 250 "$FRONT" "$FRONTC" 2>/dev/null
			fi
			if [ -f "$FRONTC" ]
			then
				echo "<a href=\"/musica/"`echo "$file" | hte`"/$FRONT\">"
				fronturi=`echo "${file}/front.jpg" | hte`
				echo "<img height=\"250\" width=\"250\" src=\""${XMLCACHEURI}${fronturi}\"">"
				echo "</a>"
			else
				echo "<img height=\"250\" width=\"250\" src=\"/musica/"`echo "$file" | hte`"/$FRONT\">"
			fi
			echo "<!-- front cover -->"
			echo "</TD>"
		fi

		if ls *mp3 > /dev/null 2>&1
		then


		if $GUI_PLAYER
		then
			echo "<!-- gui player -->"
			XMLFILE=playlist.xml
			XMLDIR="${XMLCACHE}${file}"
			test -d "${XMLDIR}" || mkdir -p "${XMLDIR}"
			XML="${XMLDIR}"/"${XMLFILE}"
			HTML51="${XMLDIR}/audio.html"
			HTML52="${XMLDIR}/player.html"
			PL=`basename "${file}"`

			if [ "${HTML52}" -nt "${PWD}" ]
			then
				:
			else

				cat > "${XML}" <<EOF
<?xml version="1.0" encoding="UTF-8"?>
<playlist version="1" xmlns="http://xspf.org/ns/0/">
    <title>$PL</title>
    <creator>$MYNAME</creator>
    <image>front.jpg</image>

    <trackList>

EOF
			XMLTRACK=0
			for f in *mp3
			do
				uri=`echo "$file"/"$f" | hte`
				xmlentry "$f" /"$uri" "$file"
				XMLTRACK=`expr $XMLTRACK + 1`
			done

			cat >> "${XML}" <<EOF
    </trackList>
</playlist>
EOF
			fi



		echo "<td>"
		
		html51tail
		cat "${HTML51}"
	
		html52tail
		cat "${HTML52}"

		echo "</td>"

		else # No swf player

			if false
			then
				if $FULL
				then
					LINK3="<A HREF=\"${MYNAME}?full=true&player=true&$QUERY_STRING\">Mostrar reproductor</A>"
				else
					LINK3="<A HREF=\"${MYNAME}?player=true&$QUERY_STRING\">Mostrar reproductor</A>"
				fi
			else
				LINK3="Cambie a vista detallada o mini para ver el reproductor"
			fi
			echo "<TD>"
			echo "$LINK3"
			echo "</TD>"
			
		fi

		if $GUI_INFO
		then
			if  [ -f info.txt ]
			then
				echo "<TD>"
				#echo "<font size='1' face='Verdana'>"

				echo '<div style="height:250px;width:350px;font:12px Verdana;overflow:scroll;">'
				charconv -fl -th < info.txt | sed -e 's/$/<br>/'
				echo '</div>'
				#echo "</font>"
				echo "</TD>"
			fi
		fi


		echo "</TR></TABLE>"

		if $GUI_M3U
		then
			cat <<-EOF
			<FORM ACTION="$MYNAME" method="POST">
			<INPUT TYPE="hidden" NAME="stream" VALUE="`echo "$file"`">
			<table>
			<tbody><tr>
			<td>Password:</td><td><input name="p" type="password"></td>
			<td><INPUT TYPE="submit" VALUE="Escuchar"></td>
			</tr>
			</table>
			<P>
			<FONT SIZE="-3">
			<B>Nota</B>:
			El reproductor de audio que utilices requiere el password.<br>
			Si se deja en blanco, lo solicitar interactivamente.<br>
			Si no, se debe borrar el fichero m3u tras escucharlo.
			</FONT>
			</P>
			</FORM>
			<P>
			EOF
		fi

		else # No mp3 data

			echo "</TR></TABLE>"

		fi
		echo "<P>"

		echo "<UL>"
		OPTSS=`echo "$OPTS" | sed -e 's/&/+++/g'`

		if $FULL
		then
			ls -d1 */ 2>/dev/null |\
			sed -e 's|\(.*\)/$|<li><STRONG><a href="'"$MYNAME?$OPTSS$fileuri/"'\1">\1</a></STRONG>|' |\
			sed -e 's/+++/\&/g' \
			-e ':begin;s/\(.*"[^"]*\) \([^"]*".*\)/\1%20\2/;t begin'
		else
			ls -ld */ 2>/dev/null |\
			egrep "^d.........[\.]*[ ]*[0-9]*[ ]*$OWNER " |\
			sed -e 's/^d.........[\.]*[ ]*[0-9]*[ ]*'"${OWNER}"' [ ]*[a-z][a-z]* [ ]*[0-9][0-9]* [ ]*[a-zA-Z][a-z]* [ ]*[0-9][0-9]* [ ]*[0-9][0-9:]*[ ]*//' \
			-e 's|\(.*\)/$|<li><STRONG><a href="'"$MYNAME?$OPTSS$fileuri/"'\1">\1</a></STRONG>|' | sed -e 's/+++/\&/g' \
			-e ':begin;s/\(.*"[^"]*\) \([^"]*".*\)/\1%20\2/;t begin'
		fi
		echo "</UL>"
		set +e

		if $GUI_FILES
		then
			if $GUI_DETAIL
			then
				echo "<table border='0' class='zebra'><tbody>"
				class=even
				tdb="<td><font size='1' face='Verdana'>"
				tde="</font></td>"
			else
				echo "<UL>"
			fi
			for f in *
			do
				if [ -f "$f" ]
				then
					uri=`echo "$file"/"$f" | hte`

					if $GUI_DETAIL
					then
						echo "<tr class='$class'>"

						if [ "$class" == "even" ]
						then
							class="odd"
						else
							class="even"
						fi

						case "$f" in
						*mp3)
						urimp3=`echo "$uri" | sed -e 's/%/%%/g'`
						mp3info -p "${tdb}%n${tde}${tdb}<a href=\"/musica/$urimp3\">%t</a>${tde}${tdb}%0.2m:%0.2s${tde}${tdb}%a-%l (%y)${tde}${tdb}%r KB/s${tde}${tdb}%q KHz${tde}${tdb}(%g)${tde}${tdb}%c${tde}${tdb}%b${tde}" "$f"
						;;
						*jpg)
							echo "${tdb}" \
								'<a href="/musica/'"$uri"'">'"$f"'</a>' \
								"${tde}${tdb}"
							jhead "$f" | awk -F: '/Resolution/{print $2}'
							echo "${tde}"
						;;
						*)
							echo "${tdb}" \
								'<a href="/musica/'"$uri"'">'"$f"'</a>' \
								"${tde}${tdb}"
							file "$f" | sed -e 's/^.*: //'
							echo "${tde}"

						;;
						esac
						echo "</tr>"
					else
						echo '<LI><a href="/musica/'"$uri"'">'"$f"'</a>'
					fi
				fi
			done

			$GUI_DETAIL && echo "</tbody></table>" || echo "</UL>"
		fi

		####
		# GRID
		
		if $GUI_DETAIL
		then
		NCOL=4
		IR=0

		echo "<br><table border=0>"

		ls -1d */01*mp3 */CD1* 2>/dev/null |\
		while read line
		do
			if [ $IR -eq 0 ]
			then
				echo "<tr>"
			fi
			f=`dirname "$line"`
			FRONT="$f"/front.jpg
			XMLDIR="${XMLCACHE}${file}/$f"
			test -d "${XMLDIR}" || mkdir -p "${XMLDIR}"
			FRONTC="${XMLDIR}"/front.jpg
			if [ -f "$FRONTC" ]
			then
				:
			else
				convert  -resize 250 "$FRONT" "$FRONTC" 2>/dev/null
			fi

			uri=`echo "$file"/"$f" | hte`
			echo "<TD align=\"center\">"
			echo "<a href=\"$MYNAME?$OPTS$uri\">"
			
			if [ -f "$FRONTC" ]
			then
				fronturi=`echo "${file}/${f}/front.jpg" | hte`
				echo "<img height=\"150\" width=\"150\" src=\""${XMLCACHEURI}${fronturi}\"">"
			else
				if [ -f "$ROOT/$file/$FRONT" ]
				then
					echo "<img height="150" width="150" src=\"/musica/"`echo "$file" | hte`"/$FRONT\">"
				else
					echo "<img height="150" width="150" src=\"${PLAYERDIR}/cds.png\">"
				fi
			fi
			echo '<br>'"$f"'</a>'
			echo "</TD>"
			IR=`expr $IR + 1`
			if [ $IR -eq $NCOL ]
			then
				echo "</tr>"
				IR=0
			fi
		done
		echo "</table>"
		fi
		
		# GRID
		####

		set -f
		set +e

		htmlfooter

	exit 0
fi
###########################################################################
#
# Finish
#

if $error
then
	htmlheader
	htmlhead Error
	
	cat << EOF
	<body>
	<H1>Invalid argument</H1>
	<P>
	Sorry, either you supplied a non valid request or the file
	doesn't exist.
	</P>
	<P>$errormsg</P>
	<P>
	Request has been logged.
	</P>
	</body>
	</html>
EOF
	exit 0
fi

