#!/bin/sh

# publish and announce given arc on the torrent web
# Intended to be run via ssh directly on hardware router (on DD-WRT + OPTWARE)

BASE="/mnt/bigstore/wwshared/thai2013"
HOST="localhost"
TMP="/mnt/tmp"
NAME="$1"
MEDIA="$2"
ADDITION="$MEDIA"

cd $BASE
echo $MEDIA
if [ "z${MEDIA}" = "z" ] ; then
    echo "Using default extension: photo"
    MEDIA='photo'
    ADDITION=''
fi

TORR="$TMP/tor.torrent"
ARC="$NAME/$NAME-$MEDIA.tar"
TARDIR="$BASE/$NAME/"

# if there is no name-photo.tar - do the torrent from all tars in folder
if [ ! -e "$ARC" ] ; then
    echo "Adding several files"
    tmdir="$TMP/$NAME"
    [ -d "$tmdir" ] && rm -rf "$tmdir"
    mkdir -p "$tmdir"
    echo "in dir $tmdir"
    olddir=`pwd`
    cd "$NAME"
    curdir=`pwd`
    for a in *.tar ; do
	echo "Adding file $a..."
	ln -s "$curdir/$a" "$tmdir/$a"
    done
    cd "$olddir"
    ARC="$tmdir"
    TARDIR="$BASE"
fi

[ -f "$TORR" ] && rm -f "$TORR"
echo "Making a torrent..."
#transmissioncli -n "$ARC" "$TORR"
transmission-create -o "$TORR" "$ARC"
HASH=`transmission-show "$TORR" | grep Hash | awk '{print $2;}'`
echo "Announce the torrent..."
transmission-remote "$HOST" -w "$TARDIR/" -a "$TORR"
echo "All is done."
[ -d "$ARC" ] && rm -rf "$ARC"
MAGNET="magnet:?xt=urn:btih:$HASH"
LABEL="$NAME"
if [ "z$ADDITION" != "z" ] ; then
    LABEL="$NAME-$ADDITION"
fi
echo "$MAGNET	$LABEL" >> magnet-torrents.txt
echo "<a href=\"$MAGNET\">$LABEL</a><br>" >> magnet-torrents.html
echo "$MAGNET"


