#!/usr/bin/perl

sub extract_file {
    $path = "";
    foreach $i (split(/\//,$_[0])) {
	$path .= "$i/";
	mkdir $path;
    }
    $entry = $_[2];
    $entry =~ m,/([^/]+)/,;
    $path .= $1;
    open HANDLE,"> $path" || die "Can not create $path.\n";
    $_ = <>;
    die "Bad file\n" unless /GET (\d+)/;
    $size = $1;
    read STDIN,$buffer,$size;
    $end = <>;
    die "Read error\n" unless defined($buffer) && length($buffer) == $size &&
	$end eq "GET DONE\n";
    print HANDLE $buffer;
    close HANDLE;
    if ($gzip) {
	print "Unzipping... ";
	system "mv $path $path.gz";
	if (system "gunzip $path.gz") {
	    print "Failed\n";
	    system "mv $path.gz $path";
	} else {
	    print "Done\n";
	}
    }
    print "Create $path ($size bytes)\n";
}

$gzip = 0;
while (<>) {
#    print ">> $_";
    chomp;
    exit 0 if $_ eq "QUIT";
    $gzip = $1 if /^CMD gzip (\d)/;
    extract_file($1,$2,$3,$4) if /^UPDATE <(.*)> <(.*)> <(.*)> <(.*)>/;
    print "$1\n" if /^MSG (.*)/;
    print STDERR "$1\n" if /^ERR (.*)/;
}
