#!/bin/sh
#
# Crude attempt to keep torrent in sync from FreeBSD RSS feed
# eq autofeed them into transmission 
# 
# Lesson learned: Shell is NOT useable for XML parsing
#
# Licence: BSDLike
# Rick van der Zwet <info@rickvanderzwet.nl>

TORRENTQUEUE=/data/transmission/upload
TORRENTRSS=${1-http://torrents.freebsd.org:8080/rss.xml}

# Cleanup bits
TMPDIR=`mktemp -d /tmp/$(basename $0).XXXXX`
RSSFILE=$TMPDIR/output.rss
trap "rm -Rf $TMPDIR; exit 1" 1 2 3 15
trap "rm -Rf $TMPDIR; exit 0" 0 


# Check for new ones
fetch -qo - $TORRENTRSS > $RSSFILE
if [ \! -s "$RSSFILE" ]; then
  echo "Failed to download RSS feed $TORRENTRSS"
  exit 1
fi

# Split based on item
awk -vTMPDIR=$TMPDIR '/<item>/{n++}{print > sprintf("%s/item.txt.%03i", TMPDIR ,n) }' $RSSFILE

# Download the new ones please, if not yet existing
for ITEM in $TMPDIR/item.txt.???; do
  URI=`awk -F\" '/^<enclosure url=/{print $2}' $ITEM`
  [ -z "$URI" ] && continue
  TITLE=`awk '/^<title>/{print $0}' $ITEM`
  TARGET=$TORRENTQUEUE/`basename $URI`
  if [ \! -r $TARGET ]; then
    echo "# Adding torrent $TARGET ($TITLE)"
    fetch -qo $TARGET $URI 
  fi
done
