#!/usr/bin/perl

use strict;
use warnings;

my $VERSION = "1.0";
my $HOME = $ENV{HOME};
my $TRACKERSFILE = "$HOME/.trackers";
my $TORRENT_COMMENT = "$HOME/.torrent_comment.txt";
my @Trackers = ();
my $MyComment = "";
my $VERBOSE = "";

print "mytorrent v$VERSION\n";
print "==================\n";

my $CurFile = "";
if ($#ARGV >= 0)
{
	$CurFile = $ARGV[0];
}
else 
{
	print "Must specify the file to process\n";
	print "Usage:\n";
	print "mytorrent \<file to use\> \[verbose\]\n";
	exit 1;
}
if ($#ARGV == 1)
{
	$VERBOSE = 1;
}

print "Loading in $HOME/.trackers:\n";
if (! -f $TRACKERSFILE)
{
	print "trackers list not found, running updater:\n";
	system("updatetrackers");
}
my $SawVersion = "";
my $NumTrackers = 0;
open my $file, '<', $TRACKERSFILE or die("Unable to open tracker file: $!");
while(<$file>)
{
	my $CurLine = $_;
	chop($CurLine);
	if ($CurLine eq "")
	{
		next;
	}
	if ($SawVersion eq "")
	{
		print "File version: $CurLine\n";
		$SawVersion = "true";
	}
	else
	{
		if ($VERBOSE)
		{
			print "Saw tracker: $CurLine\n";
		}
		push (@Trackers, $CurLine);
		$NumTrackers += 1;
	}
}
close $file;

if (! -f $TORRENT_COMMENT)
{
	print "$TORRENT_COMMENT doesn't exist, please create it with your desired comment.\n";
	exit 1;
}
open $file, '<', $TORRENT_COMMENT or die("Unable to open TORRENT_COMMENT: $!");
$MyComment = <$file>;
close ($file);
chop ($MyComment);
print "Saw $NumTrackers trackers\n";
if ($VERBOSE)
{
	print "Using comment: $MyComment\n";
}

my $TorrentCommand = "/usr/bin/transmission-create -c \"$MyComment\"";
foreach (@Trackers)
{
	$TorrentCommand = "$TorrentCommand -t \"$_\"";
}
if ($VERBOSE)
{
	print "$TorrentCommand\n";
}

$CurFile = "";
if ($#ARGV >= 0)
{
	$CurFile = $ARGV[0];
}
else 
{
	print "Must specify the file to process\n";
	exit 1;
}

if (! -f $CurFile)
{
	print "Source file \"$CurFile\" does not exist\n";
	exit 1;
}
print "Creating torrent file for $CurFile\n";

system("$TorrentCommand \"$CurFile\"");

exit 0;
