#!/bin/bash
# RockIt-Downloader ver 2010.04.23
# it automatically downloads MP3 from http://www.rockit.it
#
# Copyright (C) 2010 much0 (at) salug.it
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#

DEBUG=0			       # set to 1 to enable debug

if [ $DEBUG -eq 1 ]; then
    set -x
fi

URL=$1
ROCKITURL="http://www.rockit.it"
# oldsite
#PATTERNPLAYLIST="/mediaplayer/rockit_pl.php?"
# newsite
PATTERNPLAYLIST="%2Fmediaplayer%2Frockit_pl.php%3F"
PATTERNPLAYLISTURL="/mediaplayer/rockit_pl.php?x="
#
PATTERNCOVERIMG="href=\"/dbimg/copertine"
MISSINGDEPS=""
MISSINGDEPSFLAG=0
PLAYLIST="xmlplaylist"
TRACKLIST="tracklist"
LINKLIST="linklist"
MUSICDIR="."
NETDOWNLOADER=""		# wget | curl
OUTPUTFILEOPT=""		# -O   | -o
SILENTOPT=""			# -q   | -s

# controlla la dipendenza passata come parametro
# usage: checkdep "nome-dipendenza"
function checkdep {
    if [ "x$1" == "x" ]; then
	echo "$0: errore interno"
	exit 1
    fi

    which "$1" >/dev/null 2>&1
    if [ $? -ne 0 ]; then
	MISSINGDEPS="$MISSINGDEPS$1 "
	MISSINGDEPSFLAG=1
	return 1
    fi

    return 0
}

# controlla il valore di ritorno dell'ultimo comando eseguito
# e stampa a video la stringa passata come parametro
# (es: checkretval $retvalue "errore!")
function checkretval {
    RETURN=$1

    if [ "x$1" == "x" ] || [ "x$2" == "x" ]; then
	echo "$0: errore interno"
	cleanup
	exit 1
    fi

    if [ $RETURN -ne 0 ]; then
	echo "$0: $2"
	cleanup
	exit 1
    fi

    return 0
}

function cleanup {
if [ $DEBUG -ne 1 ]; then
    rm index.html 2>/dev/null
    rm $PLAYLIST  2>/dev/null
    rm $TRACKLIST 2>/dev/null
    rm $LINKLIST  2>/dev/null
fi
    return 0
}

# estrae il nome dell'autore
function extract_artist {
    # AUTH="$( cat index.html | awk -F">" '/titcd/ { print $34 }' | cut -d"<" -f1 )"
    AUTH="$(cat index.html | grep titcd | head -1 | cut -d'>' -f3 | cut -d'<' -f1)"
    echo "$AUTH"
}

# estrae il nome dell'album
function extract_album {
    # ALB="$( cat index.html | awk -F">" '/titcd/ { print $37 }' | cut -d"<" -f1 )"
    ALB="$(cat index.html | grep titcd | tail -1 | cut -d'>' -f2 | cut -d'<' -f1)"
    echo "$ALB"
}

############################## MAIN ################################

if [ "x$1" == "x" ]; then
    echo "Usage: $0 <URL>"
    echo "   ex: $0 http://www.rockit.it/album/13132/aavv-materiali-resistenti"
    exit 1
fi

# check delle dipendenze
checkdep "xmlstarlet"
checkdep "awk"
checkdep "grep"
checkdep "tr"
if [ $MISSINGDEPSFLAG -ne 0 ]; then
    echo "$0: dipendenze mancanti: $MISSINGDEPS"
    exit 1
fi
# check di wget o curl
checkdep "wget"
if [ $? -ne 0 ]; then
    checkdep "curl"
    if [ $? -ne 0 ]; then
	echo "$0: dipendenze mancanti: wget o curl"
	exit 1
    fi
    NETDOWNLOADER="curl"
    OUTPUTFILEOPT="-o"
    SILENTOPT="-s"
else
    NETDOWNLOADER="wget"
    OUTPUTFILEOPT="-O"
    SILENTOPT="-q"
fi

# cleanup iniziale
cleanup

# scarica la pagina html principale
$NETDOWNLOADER $SILENTOPT $OUTPUTFILEOPT index.html $URL
# estrae il link alla playlist (es: rockit_pl.php?x=a13132)
# oldsite
#PLAYLISTURL=$( cat index.html | tr ' ' '\n' | grep "$PATTERNPLAYLIST" | cut -d? -f2 | cut -d"'" -f1 )
#PLAYLISTURL=$ROCKITURL$PATTERNPLAYLIST$PLAYLISTURL
# newsite
PLAYLISTURL=$( cat index.html | tr ' ' '\n' | grep "$PATTERNPLAYLIST" | cut -dx -f2 | cut -d"'" -f1 )
PLAYLISTURL=${PLAYLISTURL:3}	# remove the '%3D' header
# URL completo (es: http://www.rockit.it/mediaplayer/rockit_pl.php?x=a13132)
PLAYLISTURL=$ROCKITURL$PATTERNPLAYLISTURL$PLAYLISTURL
#
# scarica la pagina della playlist
$NETDOWNLOADER $SILENTOPT $OUTPUTFILEOPT $PLAYLIST $PLAYLISTURL


AUTHOR="$(extract_artist)"
ALBUM="$(extract_album)"

# crea la directory di destinazione dei file MP3
if [ "x$AUTHOR" != "x" ] && [ "x$ALBUM" != "x" ]; then
    MUSICDIR=$( echo "$AUTHOR"" - ""$ALBUM" | tr '/' '_' )
    echo -e "Autore - Album: \033[33;40;1m$MUSICDIR\033[0m\n"
    mkdir "$MUSICDIR" 2>/dev/null
fi

# parsing XML
TEMP=$( xmlstarlet fo -e utf-8 "$PLAYLIST" 2>/dev/null )
checkretval $? "errore nel parsing dell'XML"
# estrae il nome delle tracce
echo "$TEMP" |\
  grep title | grep -v "Rockit Playlist"  |\
  cut -d'>' -f 2 | cut -d'<' -f1 \
  > $TRACKLIST
# estrae gli URL
echo "$TEMP" |\
  grep url |\
  cut -d\" -f2 \
  > $LINKLIST

# controllo numero tracce/url
NUMTRACKS=$( cat $TRACKLIST | wc -l )
NUMLINKS=$( cat $LINKLIST | wc -l )
if [ $NUMTRACKS -ne $NUMLINKS ]; then
    echo "$0: errore nel parsing dell'XML"
    cleanup
    exit 1
fi

# download cover image
COVERIMGURL=$( cat index.html | tr ' ' '\n' | grep "$PATTERNCOVERIMG" | cut -d'"' -f2 )
if [ "x$COVERIMGURL" != "x" ]; then
    $NETDOWNLOADER $SILENTOPT $OUTPUTFILEOPT "$MUSICDIR"/cover.jpg $ROCKITURL$COVERIMGURL
fi

# download songs
i=1
while [ $i -le $NUMTRACKS ]; do
    URL="$( cat $LINKLIST | head -$i | tail -1 )"
    TRACKNAME="$( cat $TRACKLIST | head -$i | tail -1 | tr '/' '_' )"
    echo -e "\033[33;40;1m(download $i/$NUMTRACKS) $TRACKNAME\033[0m"
    $NETDOWNLOADER $OUTPUTFILEOPT "$MUSICDIR"/"$TRACKNAME".mp3 $URL
    i=$(($i + 1))
done
echo -e "$0: Download di \033[33;40;1m$NUMTRACKS tracce\033[0m completato."

# cleanup finale
cleanup

exit 0

