#!/usr/bin/perl

# get-jpeg version 0.1

# Copyright (C) 2008, ashley willis <barry@venamous.net>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
# or FITNESS FOR A PARTICULAR PURPOSE.
#
# See the GNU General Public License in the COPYING file at the
# root directory of this project for more details.

# downloads all JPEG files in 'Content Store' to current directory.

#$HEAD = 0;

@dump = `btool -d 'Content Store'`;
@converted = convertDump(@dump);

# open $fh, "<", \$text;
# while (<$fh>) { #... }

foreach $file (@converted) {
  open(IN, "<", \$file);
  $jpeg = 0;
  read(IN, $head, 3);
  if ($head =~ /^! $/) {	# barrybackup data, ipd2tgz
    $header = $head;
  }
  else {
    read(IN, $header, 15);
    $header = $head . $header;
  }

  ($name, $remainder) = split(/ /, <IN>, 2);
  ($name =~ /\.jpg$/) or next;

  $remainder = " $remainder";
  #print "NAME=$name\n";
  if ($remainder =~ //) {
    ($remainder, $jpeg) = split(//, $remainder, 2);
    $head = $header . $name . $remainder;
    #if ($HEAD) {
    #  open(OUT, ">file.head") or die "Cannot create header file: file.head\n";
    #  print OUT $head;
    #  close(OUT);
    #}
    open(OUT, ">file.jpg") or die "Cannot create jpeg file: file.jpg\n";
    print OUT "$jpeg";
  }

  $head = $header . $name . $remainder;

  while (<IN>) {
    if (!$jpeg and //) {
      ($remainder, $jpeg) = split(//);
      $head .= $remainder;
      #if ($HEAD) {
      #  open(OUT, ">file.head") or die "Cannot create header file: file.head\n";
      #  print OUT $head;
      #  close(OUT);
      #}
      open(OUT, ">file.jpg") or die "Cannot create jpeg file: file.jpg\n";
      print OUT "$jpeg";
    }
    elsif (!$jpeg) {
      $head .= $_;
    }
    else {
      print OUT;
    }
  }
  close(OUT);
  close(IN);

  open(IN, "file.jpg");
  $name =~ s/^.*\///;
  open(OUT, ">$name") or die "Cannot create jpeg file: $name\n";
  do {
    $count = read(IN, $jpg, 65535);
#    print "$name: COUNT=$count\n";
    print OUT $jpg;
    read(IN, $head, 3);
  } while ($count == 65535);
  close(OUT);
  close(IN);
  unlink("file.jpg");
}


# convert-dumps
sub convertDump() {
  my @data = @_;
  my $record = -1;
  my @out;
  foreach (@data) {
    if (/^Raw record dump for record: /) {
      $record++;
    }
    if (/^    0/) {
      s/^    0[\da-f]{7}: //;
      s/  .*\n//;
      s/ //g;
      $out[$record] .= pack("H*", $_);
    }
  }
  return @out;
}
# end convert-dumps
