#!/bin/sh
#
# Crude attempt to keep torrent in sync from FreeBSD URL 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
TORRENTURL=${1-http://torrents.freebsd.org:8080}

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


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

TORRENTS=`awk -F'"' '/.torrent"/ {print $8}' $URLFILE`

# Download the new ones please, if not yet existing
for TORRENT in $TORRENTS; do
  TARGET=$TORRENTQUEUE/`basename $TORRENT`
  URI=$TORRENTURL$TORRENT
  if [ \! -r $TARGET ]; then
    echo "# Adding torrent $TARGET ($URI)"
    fetch -qo $TARGET $URI 
  else
    echo "# Torrent $TARGET already exist"
  fi
done
