#!/usr/bin/env perl
#
# Show a cute progressbar for cg-fetch.
# Copyright (c) Petr Baudis, 2005
#
# This file shows a progressbar for cg-fetch based on output of rsync
# or native git fetchers. It is written in perl because I cannot figure
# out a way to check a file size without slowing the fetch by a factor
# of four.

use warnings;
use strict;

# Even line-buffering is bad since we output no newlines normally.
$| = 1;

my $_git_objects = shift;

my $objects = 0;
my $last_objects = 0;
my $size = 0;
my $percentage = '';

while (<>) {
	my $object = '';

	chomp;

	# git fetcher
	if (m#^(link|symlink|copy|got) ([a-f0-9]{2})([a-f0-9]{38})#) {
		$object = "$2/$3";

	} elsif (m#^(walk) ([a-f0-9]{2})([a-f0-9]{38})#) {
		next; # redundant information

	# rsync
	} elsif (m#^([a-f0-9]{2})/([a-f0-9]{38})$#) {
		$object = $_;
		# Estimate percentage done using the position of
		# the object subdir. It might not get all the way
		# up to 100% ...
		$percentage = ', ' . int(hex($1) * 100 / 0xff) . '% done';

	# some rsync versions output this
	} elsif (m#^([a-f0-9]{2})/$#) {
		next;

	# misc. output
	} else {
		if ($last_objects != $objects ) {
			$last_objects = $objects;
			print "\n";
		}
		print "$_\n";
		next;
	}

	$object = "$_git_objects/$object";
	-e $object and $size += (stat($object))[7];
	$objects++;

	print "progress: $objects objects, $size bytes$percentage\r";
}

$last_objects != $objects and print "\n";
