#!/usr/bin/perl -w
use strict;

open I, "debian/control" or die $!;
open O, ">debian/control.new" or die $!;

our %need_features = qw(
    clap +derive
    env-logger +default
		      );
our %replace = (
    clap => 'librust-clap-3+derive-dev',
	       );

while (<I>) {
  if (m{^\# debian/update-build-deps}i...m{^\S}) {
    next if m{^ +librust[-+a-z0-9]+ (?:\(.*\) )?\<!upstream-cargo\>,?\s*$};
    if (m{^\S} && !m{^\#}i) {
      local ($_);
      open C, "Cargo.toml" or die $!;
      while (<C>) {
	next unless m{^\[dependencies\]} ... m{^\[};
	next unless m{^\s*([-_0-9a-z+]+)\s*=};
	my $p = $1;
	next if m{path ?= ?\"};
	$p =~ y/_/-/;
	my $dep = $replace{$p};
	if (!defined $dep) {
	  my $f = $need_features{$p} // '';
	  $dep = "librust-$p$f-dev";
	}
	if (length $dep) {
	  print O "    $dep <!upstream-cargo>,\n" or die $!;
	}
      }
      C->error and die $!;
    }
  }
  print O or die $!;
}

I->error and die $!;
close O or die $!;
rename "debian/control.new", "debian/control" or die $!;
