#!/usr/bin/perl
#
# Implement workaround for bug #765577 by removing duplicate entries
# from the persistent network interface name rule before rebooting for
# the first time, to make sure eth0 is present on the machines with
# fixed network setup in /etc/network/interfaces

use strict;
use warnings;
use Getopt::Std;

my $bugurl = "https://bugs.debian.org/765577";

my $rulefile = "/etc/udev/rules.d/70-persistent-net.rules";
my $newfile = "$rulefile.new";

my $debug = 0;
my %linecache;
my $modified = 0;
my %opts;

sub usage {
    my $retval = shift;
    print <<EOF;
Usage: $0: [-dn]
Fix
  -d   enable debugging
  -n   do not modify $rulefile
EOF
  exit($retval) if $retval;
}

getopts("dn", \%opts) || usage(1);

open(my $rh, '<', $rulefile) || die "error: unable to read from $rulefile";
my $wh;
if (!$opts{'n'}) {
    open($wh, '>', "$newfile") || die "error: unable to write to $newfile";
}
my $shortline;
while (my $line = <$rh>) {
    $shortline = $line;
    $shortline =~ s/, NAME="[^"]+"//;
    print STDERR "shortline: '$shortline'\n" if $opts{'d'};
    if ($shortline !~ m/^\s*$/
        && $shortline =~ m/^SUBSYSTEM=/
        && exists $linecache{$shortline}) {
        # Seen the same line before, skip it.
        print STDERR "skipping line\n" if $opts{'d'};
        $modified = 1;
        if (!$opts{'n'}) {
            print $wh "# Duplicate entry disabled, workaround for $bugurl\n#$line";
        }
        next;
    }
    $linecache{$shortline} = 1;
    if (!$opts{'n'}) {
        print $wh $line;
    }
}
close($rh);
if (!$opts{'n'}) {
    close($wh);
    if ($modified) {
        rename("$newfile", "$rulefile") || die "error: unable to rename $newfile to $rulefile";
    } else {
        unlink $newfile;
    }
} else {
}
exit ! $modified;
