#! /usr/bin/perl -w

use strict;
use warnings;

my $cachefile = shift @ARGV || die "usage: $0 cache.file [filename.to.save]";
if (! -r $cachefile) {
    die "$0: cannot read $cachefile";
}
my $savefile = shift @ARGV;

open CACHE, "<$cachefile";


my $hrcount = 2;
my $filename;
my $line;
while ($hrcount > 0) {
    $line = <CACHE>;
    if ($line =~ /<hr>/) { $hrcount--; }
    if ($line =~ /https?:.+\/([^\/<]+)</) {
        $filename = $1;
    }
    if ($line =~ /Content-Disposition:.+filename=(&quot;)?([\w.]+)(&quot;)?/) {
        $filename = $2;
    }
}
print STDERR "$0: filename from cache: '$filename'\n";
if (! $savefile) {
    $savefile = $filename;
}
print STDERR "$0: save file to '$savefile'\n";

$hrcount = 1;
while ($hrcount > 0) {
    $line = <CACHE>;
    if ($line =~ /<hr>/) { $hrcount--; }
}

$line = substr $line, 15;

open SAVE, ">$savefile" || die "$0: cannot write $savefile";
binmode(SAVE);

$hrcount = 1;
while ($hrcount > 0) {
    print SAVE hex2bin($line);
    
    $line = <CACHE>;
    if ($line =~ /<hr>/) { $hrcount--; }
}

print STDERR "$0: done\n";

sub hex2bin {
    my $str = shift @_;
    
    $str = substr $str, 11, 64;
    
    return pack("H*", join("", split(" ", $str)));
}
