#!/bin/bash

CACHEDIR=ytpodcast

if [[ $# -ne 1 ]]; then
    echo "Väärä määrä parametreja ($#, pitää olla 1 podcastsyötteen osoite)."
    exit 1
fi



test -x $HOME/.cache || { echo "Y U NO ~/.cache?"; exit 1; }
CACHEDIR=$HOME/.cache/${CACHEDIR%%/}
test -x "${CACHEDIR}/episodes" || { mkdir -p "${CACHEDIR}/episodes" || { echo "Y U NO mkdir?"; exit 1; } }
cd "${CACHEDIR}" || { echo "Y U NO cd ${CACHEDIR}?"; exit 1; }

NEW=$(mktemp /tmp/XXXXXXXXXX.xml)
export DBUS_SESSION_BUS_ADDRESS=$(cat /proc/$(pidof gnome-session)/environ | tr '\0' '\n' | grep DBUS_SESSION_BUS_ADDRESS | cut -d '=' -f2-)

/usr/bin/wget -o /dev/null -O "${NEW}" "${1}" || { echo "Y U NO wget?"; exit 1; }
CHANNEL=$(grep -A 1 "<channel" "${NEW}" | tail -n 1 | cut -d\> -f 2 | cut -d\< -f 1 | iconv -f utf-8 -t ascii//translit | sed 's/[^a-zA-Z0-9]/_/g')



function purge() {
    DL=$(gsettings get org.gnome.rhythmbox.podcast download-location)
    test -n "${DL}" || { echo "Y U NO rhythmbox?"; return 1; }

    DL=$(echo ${DL} | sed "s/^\([\"\']\)\(.*\)\1\$/\2/g" | perl -pi.back -MURI::Escape -e 'y/+/ /;$_=uri_unescape$_')
    DL="${DL:7}"
    test -r "episodes/${CHANNEL}/old-guids.txt" || return 0
    pushd "episodes/${CHANNEL}" > /dev/null
    while read guid
    do
        N=$(find "${DL}" -name '*'${guid/_/-}'*' | wc -l)
        test "$N" == "1" && find . -name "${guid}.*" -exec gvfs-trash -- {} \;
    done < old-guids.txt
    popd > /dev/null
    return 0
}
purge
EXITCODE=$?
test "$(basename "${0}")" != "ytpodcastpurge" || exit $EXITCODE



function get_guids() {
    grep "<guid" "${1}" | cut -d\: -f 3 | cut -d\< -f 1 | sort
}

function add_item() {
    ITEM=item.xml
    echo "          <item>" > "${ITEM}"
    echo "${1}" >> "${ITEM}"
    echo "${2}" >> "${ITEM}"
    echo "               <link>http://www.youtube.com/watch?v=${3}&amp;feature=youtube_gdata</link>" >> "${ITEM}"
    echo "               <enclosure url=\"file://${CACHEDIR}/episodes/${CHANNEL}/${4}\" length=\"${5}\" type=\"${6}\" />" >> "${ITEM}"
    echo "          </item>" >> "${ITEM}"
    cat "${ITEM}" >> new-mid.xml
}

AVCONV_DIR=/tmp/ytpodcast-tools
AVCONV=${AVCONV_DIR%%/}/avconv
AVCONV_QUIET=/usr/local/bin/avconv-quiet
if [[ ! -x "${AVCONV}" ]]; then
        test -x "${AVCONV_QUIET}" || { echo "Y U NO avconv-quiet?" ; exit 1 ; }
        mkdir -p "${AVCONV_DIR}"
        ln -s "${AVCONV_QUIET}" "${AVCONV}"
fi
test -x "${AVCONV}" ||{ echo "Y U NO avconv?" ; exit 1 ; }

mkdir -p "episodes/${CHANNEL}" || { echo "Y U NO mkdir episodes/${CHANNEL}?"; exit 1; }
cd "episodes/${CHANNEL}" || { echo "Y U NO cd $(pwd)/episodes/${CHANNEL}?"; exit 1; }
test -r old-guids.txt || touch old-guids.txt
get_guids "${NEW}" | LC_ALL=C sort > new-guids.txt
LC_ALL=C comm -13 old-guids.txt new-guids.txt > news.txt
cat new-guids.txt old-guids.txt > old-guids.txt.new
LC_ALL=C sort old-guids.txt.new | uniq > old-guids.txt

test ! "$(ls -nl news.txt | awk '{print $5}')" -eq 0 || exit 0

notify-send -i down "ytpodcast" "Uusia ladataan kanavalle ${CHANNEL}."

ITEMSTART=$(grep -m 1 -n "<item" "${NEW}" | cut -d\: -f 1)
head -n $((${ITEMSTART} - 1)) "${NEW}" > new-head.xml
echo -n "" > new-mid.xml
tac "${NEW}" > wen
sed "/<\/channel>/q" wen > wen2
tac wen2    > new-tail.xml
rm wen wen2 # this is stupid, but piping breaks when run from cron

while read guid
do
    /usr/bin/youtube-dl --avconv-location "${AVCONV}" -f bestaudio -q -w -o "%(id)s.%(ext)s" "https://www.youtube.com/watch?v=${guid}" || { rm -f -- ${guid}.{m4a,webm}.part; echo "failed to youtube-dl -f bestaudio 'https://www.youtube.com/watch?v=${guid}'?"; continue; }
    rm -f -- "${guid}.thumb.webm"
    test -r "${guid}.webm" && { /usr/bin/avconv -y -i "./${guid}.webm" "./${guid}.m4a" > /dev/null 2>&1; rm -f -- "${guid}.webm"; }
    test -r "${guid}.m4a" || { echo "Y U NO ${guid}.m4a?"; continue; }
    TITLE=$(grep -B 1 -- "${guid}" "${NEW}" | head -n 1)
    DATE=$(grep -A 1 -- "${guid}<" "${NEW}" | tail -n 1)
    TOUCHDATE=$(echo "${DATE}" | cut -d \> -f 2 | cut -d \< -f 1)
    touch -c -d "${TOUCHDATE}" -- "${guid}.m4a"
    LENGTH=$(ls -nl -- "${guid}.m4a" | awk '{print $5}')
    TYPE=$(gvfs-info -a "standard::content-type" -- "${guid}.m4a" 2>/dev/null | tail -n 1 | cut -d\  -f 4)
    add_item "${TITLE}" "${DATE}" "${guid}" "${guid}.m4a" "${LENGTH}" "${TYPE}"
done < news.txt
cat new-head.xml > news.xml
if [[ -r old-mid.xml ]]; then
    cat old-mid.xml >> new-mid.xml
fi
cat new-mid.xml > old-mid.xml
cat new-mid.xml >> news.xml
cat new-tail.xml >> news.xml
