%# Osborn's Law:
%#       Variables won't; constants aren't.
<%INIT>
my $dir = "$RT::VarPath/Foundry/download";
mkdir $dir unless -d $dir;
my $arg = $m->dhandler_arg || $r->uri;                # get rest of path
$arg =~ m!\b(\d+)/(\d+)/([^/]+)! or Abort("Corrupted attachment URL");

my ($trans, $attach, $file) = ($1, $2, $3);

if (!-e "$dir/$trans/$attach/$file") {
    my $obj = $m->comp("/Work/Tickets/Attachment/dhandler", %ARGS, NoUI => 1) or $m->abort;

    mkdir "$dir/$trans";
    mkdir "$dir/$trans/$attach";

    open(my $fh, '>:raw', "$dir/$trans/$attach/$file") or Abort($!);
    print $fh $obj->OriginalContent;
    close $fh;

    $QueueObj = $obj->TransactionObj->TicketObj->QueueObj;
}
else {
    my $TransactionObj = RT::Transaction->new($session{CurrentUser});
    $TransactionObj->Load($trans);
    $QueueObj = $TransactionObj->TicketObj->QueueObj;
}

my $AttributeObj = RT::Attribute->new($QueueObj->CurrentUser);
$AttributeObj->LoadByCols(
    Name => 'Download',
    ObjectId => $attach,
    ObjectType => 'RT::Attachment',
);

my $count_all = $QueueObj->Attribute('Download');
my $count_this = $AttributeObj->Id ? $AttributeObj->Description : 0;
if ($count_all < $count_this) {
    $QueueObj->SetAttribute('Download', $count_this + 1);
}
else {
    $QueueObj->SetAttribute('Download', $count_all + 1);
}

if ($AttributeObj->Id) {
    $AttributeObj->SetDescription( $count_this + 1 );
}
else {
    $AttributeObj->Create(
        Name => 'Download',
        ObjectId => $attach,
        ObjectType => 'RT::Attachment',
        Description => $count_this + 1,
    );
}

$m->redirect("/Foundry/Download/$trans/$attach/$file");
</%INIT>
<%ATTR>
AutoFlush => 0
</%ATTR>
<%ARGS>
$QueueObj
</%ARGS>
