#!/usr/bin/perl
if($ARGV[0] eq "")
{
        print "Usage: unpack.pl <filename>\n";
}
else
{
        print "Unpacking: $ARGV[0]\n";
        open IN, "$ARGV[0]" or die "Can't open $ARGV[0] does it exist?";
        binmode IN;
        seek IN, 4, 0; # Skip 4 byte archive header 0xAFAFAFAF

        while(!eof(IN))
        {
                $buf = "";
                $filename = "";

                # Get start of file header
                read IN, $data, 4;
                if($data ne chr(0xaa) . chr(0x55) . chr(0xAA) . chr(0x55))
                {
                        die "Can't find start of file header, got $data instead\n";
                }

                # Get filename
                $end = 0;
                while($end == 0)
                {
                        read IN, $data, 1;
                        if($data eq chr(0))
                        {
                                $end = 1;
                        }
                        else
                        {
                                $filename .= $data;
                        }
                }

                $filename = substr($filename, 1, (length($filename) - 1)); # remove leading slash and trailing nul.

                # Get file length
                read IN, $data, 4;
                $length = unpack("V", $data);
                print " Extracting: $filename - Length: $length\n";

                # Grab the actual file.
                read IN, $buf, $length;

                # Create directory tree if it doesn't already exist - not the most efficient way!)
                $path = $filename;
                $path =~ s/(.+)\/.+$/$1/g;
                system("mkdir -p $path");

                open OUT, ">$filename" or die "Can't create output file $filename\n";
                binmode OUT;
                syswrite OUT, $buf, $length or die "Can't write to output file\n";
                close OUT;
        }

close IN;
}
exit(0);