#!/usr/bin/env perl
#
# usage: chkey.pl <database> <oldkey> <newkey>
# have <newkey> reissue all certs signed by <oldkey>
#

$db = $ARGV[0];
$oldkey = $ARGV[1];
$newkey = $ARGV[2];

# handles the subset of basic_io where each item has exactly one "" argument
# /[^"]*"(([^\\"]|\\"|\\\\)*)"/
# $1 is the contents of the "" string
sub parse_restricted_basic_io {
	my $str = $_[0];
	my $beg = $_[1];
	my @out;
	my $cur = {};
	my $f = 1;
	while ($str =~ /\W*(\w+)[\w"]*/) { #"
		my $name = $1;
		$str = $';#'
		$str =~ /[^"]*"(([^\\"]|\\"|\\\\)*)"/;#"
		my $val = $1;
		$str = $';#'
		if ($name eq  $beg) {
			if ($f == 0) {
				@out = (@out, $cur);
			}
			$cur = {};
			$f = 0;
		}
		$cur->{$name} = $val;
	}
	if ($f == 0) {
		@out = (@out, $cur);
	}
	return @out;
}

$count = 0;
open $revs, "monotone -d $db auto select i: |";
while (<$revs>) { chomp; @revlist = (@revlist, $_); }
foreach my $r (@revlist) {
	chomp $r;
	my $str = `monotone -d $db auto certs $r`;
	my @res = parse_restricted_basic_io($str, "key");
	#my $p = 0;
	foreach my $rr (@res) {
		if ($rr->{"key"} eq $oldkey) {
			#print "$r\n" if ($p == 0);
			#$p = 1;
			my $name = $rr->{"name"};
			my $val = $rr->{"value"};
			#print "'$name' = '$val'\n";
			system "monotone -d $db cert $r \"$name\" \"$val\" -k $newkey";
			++$count;
			print "Certs processed: $count              \r";
		}
	}
}
print "\n";
