#!/usr/bin/perl -w

use File::Basename;

unless ($ARGV[0] =~ /\.changes$/) {
  die "Syntax: debsigs-signchanges filename.changes";
}

my $changesfile = $ARGV[0];
my $changespath = (fileparse($changesfile))[1];
my $newchangesfile = "$changesfile.debsigs-signchanges.$$";
my $ADDSIG = $ENV{DEBSIGSSIG} ? $ENV{DEBSIGSSIG} : 'maint';
my $DEBSIGSOPTIONS = $ENV{DEBSIGSOPTIONS} ? $ENV{DEBSIGSOPTIONS} : '';
open(CHANGES, "<$changesfile") or die "Couldn't open $changesfile: $!";
open(NEWCHANGES, ">$newchangesfile") or
  die "Couldn't open $newchangesfile: $!";


# Look for the Files section.

my $line;
while (defined($line = <CHANGES>) && !($line =~ /^Files:/)) {
  print NEWCHANGES $line;
}

# Print out the Files: line.

print NEWCHANGES $line;

# Now process each.

while (defined($line = <CHANGES>)) {
  my $cline = $line;		# Make a backup.
  chomp $cline;			# Chomp trailing NL.
  $cline =~ s/^ //;		# Chomp leading space.
  my ($md5sum, $size, $section, $priority, $file) = split(' ', $cline);
  unless ($file) {		# Bail if it's not a File.
    print NEWCHANGES $line;
    last;
  }
  unless ($file =~ /\.deb$/) {	# Pass through if it's not a .deb.
    print NEWCHANGES $line;
    next;
  }
  
  # OK, so it's a .deb.... process.

  print "Changespath is '$changespath'\n";

  print "Signing $file...\n";
  system("debsigs $DEBSIGSOPTIONS --sign=$ADDSIG $changespath/$file") &&
    die "Couldn't sign $changespath/$file";
  
  # Now generate the .changes line.
  $md5sum = `md5sum $changespath/$file`;
  $md5sum =~ s/\s.*$//s;	# Strip off the trailing stuff. /
  $size = (stat("$changespath/$file"))[7];
  print NEWCHANGES " $md5sum $size $section $priority $file\n";
}

# The rest of the file.

while (defined($line = <CHANGES>)) {
  print NEWCHANGES $line;
}

close CHANGES;
close NEWCHANGES;

rename($newchangesfile, $changesfile) or 
  die "Couldn't rename $newchangesfile to $changesfile: $!";
