#!/bin/sh

if [ $# -lt 2 ]
then
	echo "Usage: ./sort_a51.sh ADVANCE_PARAMETER lfsr_name [input_files_glob]"
	exit
else
	advance_parameter=$1
	lfsr_param=$2
fi

if [ "$lfsr_param" != "lfsr" -a "$lfsr_param" != "lfsr2" ]; then
	echo lfsr_name must be lfsr or lfsr2
	exit
fi

if [ $# -gt 3 ]; then
	echo "input files must be single file or unexpanded glob expression"
	echo "For example: data\\*"
	exit
fi

if [ $# -gt 2 ]; then
	input=$3
else
	input=data
fi

if ! which mktorrent >/dev/null; then
	echo "mktorrent not found, skipping torrent generation"
	exit
fi

A51TABLE=a51table

if ! which a51table >/dev/null && ! test -x a51table; then
	echo "Cannot find the a51table executable in the PATH or the current directory."
	exit
fi
if ! which a51table > /dev/null; then
	A51TABLE=./a51table
fi

# Stop table generation
# a51table signal --shutdown 

echo Make shure that you stopped the generator for this table and press enter
read foo

# Sort the table
# Check this page if you generated the table with non-default options:
# http://reflextor.com/trac/a51/wiki/RunningTheProgram#Sortingatable
consume_opt="file:prefix=sorted:startbits=53:truncstart=msb:endbits=49:truncend=lsb:indexbits=25:force"
ram=256
parts=256

rm sorted.*

$A51TABLE --advance $advance_parameter --work file:prefix=$input --icondition accept --device shortcircuit --consume $consume_opt copy --intermediate sort:parts=$parts:final:ram=$ram

# These steps are optional, only needed when several parts where generated
#cat data*.start.tbl > data_unsorted.start.tbl 
#cat data*.end.tbl > data_unsorted.end.tbl 

# Check that the values in the table are valid
skip=12345

$A51TABLE --work file:prefix=sorted:startbits=53:truncstart=msb:endbits=49:truncend=lsb:indexbits=25:skip=${skip}:limit=10 --device shortcircuit copy 

# Move all files for torrent into sub-directory
dir=a51_rt_${advance_parameter}
rm -r $dir
mkdir $dir

if [ "$lfsr_param" != "lfsr2" ]; then
	sed -i 's/lfsr2/lfsr/' sorted.table
fi

mv sorted.start.tbl $dir
mv sorted.end.tbl $dir
mv sorted.index $dir
mv sorted.table $dir

# Create torrent
if which mktorrent >/dev/null; then
	rm a51_rt_$advance_parameter.torrent
	mktorrent -l 21 -n a51_rt_$advance_parameter -a http://z6gw6skubmo2pj43.onion:8080/announce,http://z6gw6skubmo2pj43.tor2web.com:8080/announce,http://tracker.openbittorrent.com/announce,udp://tracker.openbittorrent.com:80/announce $dir 
else
	echo "torrent generation skipped. suggested parameters for a torrent are:"
	echo "Tracker list:"
	echo "\thttp://tracker.openbittorrent.com/announce"
	echo "\tudp://tracker.openbittorrent.com:80/announce"
	echo "\thttp://z6gw6skubmo2pj43.onion:8080/announce"
	echo "\thttp://z6gw6skubmo2pj43.tor2web.com:8080/announce"
	echo "Piece size: 2MB"
	echo "Torrent name a51_rt_$advance_parameter"
	echo "layout: a51_rt_$advance_parameter containing the sorted.* files"
fi


# Clean up

