#!/bin/bash
# Written by Peter Garceau
# Based on the RDF Feed Display Script by Hellf[i]re v0.1
#
# This script is designed for the Arch Linux News Feed.
# 
# This script depends on curl.
# pacman -Sy curl
#
# Usage:
# .conkyrc:    ${execi [time] /path/to/script/conky-rss.sh}
#
# Usage Example        
#        ${execi 300 /home/youruser/scripts/conky-rss.sh}

#Try to download feed
RES=$(curl -fs https://www.archlinux.org/feeds/news/)
SUCCESS=$?
if [ $SUCCESS == 0 ]
then
    echo $RES > ~/.conky/arch/cache
fi

#RSS Setup
LINES=4    #Number of headlines

FEED=$(cat ~/.conky/arch/cache)

if [ "$FEED" ]
then
    IFS=$'\n'
    TITLES=($(echo $FEED |
        sed -e 's/></>\n</g' |
        sed -n '/<title>/p'))

    ITEMS=($(echo $FEED |
        sed -e 's/<item>/\n<item>/g'))

    unset IFS

    OUTPUT='1'
    i=1
    while [ $i -le $LINES ]
    do
        OUTPUT+='\n'
        OUTPUT+=$(echo ${TITLES[$i]} | sed -n '/<title>/p' | \
            sed -e 's/<title>//' | sed -e 's/<\/title>//')
        OUTPUT+='\n'
        OUTPUT+=$(echo ${ITEMS[$i]} | sed -e 's/.*<pubDate>\(.*\)<\/pubDate>.*/\1/' | \
            awk '{print $1 " " $2 " " $3}')
        OUTPUT+='\n'
        OUTPUT+=$(echo ${ITEMS[$i]} | sed -e 's/.*<description>\(.*\)<\/description>.*/\1/' | \
            sed -e 's/&lt;\/p&gt; &lt;p&gt;/\n/g' | sed -e 's/&lt;\/p&gt;//g' | \
            sed -e 's/&lt;p&gt;//g')

        i=$(($i + 1))
    done
    echo -e $OUTPUT
    echo -e $OUTPUT | sed -e 's/&lt;/</g' | sed -e 's/&gt;/>/g' | \
        sed -e 's/<ul>/\\n/g' | sed -e 's/<\/ul>/\\n/g' | sed -e 's/<li>/\\n• /g' | sed -e 's/<\/li>//g' | \
        sed -e 's/<a href=[^>]*>/\\3/g' | sed -e 's/<\/a>/\\d/g' | \
        sed -e 's/<strong>/\\b/g' | sed -e 's/<\/strong>/\\r/g' | \
        sed -e 's/<pre>//g' | sed -e 's/<\/pre>//g' | \
        sed -e 's/<code>/\\i/g' | sed -e 's/<\/code>/\\r/g' \
        > ~/.conky/arch/feed
fi
#Do not update anything if curl fails
