#!/usr/bin/perl -w

# script to remove * <filename> comments;
# use: perl remove_embedded_filenames.pl <paths|files>
# e.g.: perl remove_embedded_filenames.pl drivers/net/ethernet/intel

use strict;

my $P = $0;
my $modified = 0;
my $quiet = 0;

sub expand_tabs {
    my ($str) = @_;

    my $res = '';
    my $n = 0;
    for my $c (split(//, $str)) {
	if ($c eq "\t") {
	    $res .= ' ';
	    $n++;
	    for (; ($n % 8) != 0; $n++) {
		$res .= ' ';
	    }
	    next;
	}
	$res .= $c;
	$n++;
    }

    return $res;
}

my $args = join(" ", @ARGV);
my $output = `git ls-files -- $args`;
my @files = split("\n", $output);

foreach my $file (@files) {
    my $f;
    my $cvt = 0;
    my $text;

# read the file

    next if ((-d $file));

    open($f, '<', $file)
	or die "$P: Can't open $file for read\n";
    $text = do { local($/) ; <$f> };
    close($f);

    next if ($text eq "");

# Remove the embedded filenames

    # remove individual lines like /* filename */ completely
    $cvt += $text =~ s@/\*[ \t]+(?:linux\/)?\Q$file\E[ \t]*\*/[ \t]*\n@@g;
    pos($text) = 0;
    # remove filenamee from /* filename -- comment */, leave /* comment */
    $cvt += $text =~ s@/\*([ \t]+)(?:linux\/)?\Q$file\E[ \t]*[:-]+[ \t]*@/*$1@g;
    pos($text) = 0;
    # remove filename and any trailing ' *\n' from /* filename, leave /*
    $cvt += $text =~ s@/\*([ \t]+)(?:linux\/)?\Q$file\E[ \t]*\n([ \t]*\*[ \t]*\n)*(?:[ \t]*\*)?@/*@g;
    pos($text) = 0;
    # remove filename from /* filename, leave /*
    $cvt += $text =~ s@/\*([ \t]+)(?:linux\/)?\Q$file\E[ \t]*\n@/*@g;
    pos($text) = 0;
    # remove filename from continuation ' * filename -- comment'
    # leave ' * comment'
    $cvt += $text =~ s/([ \t]+)\*([ \t]*)(?:linux\/)?\Q$file\E[ \t]*[:-]+[ \t]*/$1*$2/g;
    pos($text) = 0;
    # remove filename and any trailing ' *\n' from
    # continuation ' * filename\n *\n'
    $cvt += $text =~ s/([ \t]*)\*([ \t]*)(?:linux\/)?\Q$file\E[ \t]*\n([ \t]*\*[ \t]*\n)*//g;
    pos($text) = 0;

# write the file if something was changed

    if ($cvt > 0) {
	$modified = 1;
	print("$file\n");
	open($f, '>', $file)
	    or die "$P: Can't open $file for write\n";
	print $f $text;
	close($f);
    }
}

if ($modified && !$quiet) {
    print <<EOT;

Warning: these changes may not be correct.

These changes should be carefully reviewed manually and not combined with
any functional changes.

Compile, build and test your changes.

You should understand and be responsible for all object changes.

Make sure you read Documentation/SubmittingPatches before sending
any changes to reviewers, maintainers or mailing lists.
EOT
}
