#!/bin/bash

license_script=$(mktemp -t convert-SPDX-licenses.XXXXXXXXX.pl)
cat <<'EOF' >> $license_script

our $balanced_parens = qr/(\((?:[^\(\)]++|(?-1))*\))/;

sub deparenthesize {
	my ($string) = @_;

	return "" if (!defined($string));

	while ($string =~ /^\s*\(.*\)\s*$/) {
		$string =~ s@^\s*\(\s*@@;
		$string =~ s@\s*\)\s*$@@;
	}

	return $string;
}

for my $filename (@ARGV) {
	my $FILE;

	if ($filename eq '-') {
		open($FILE, '<&STDIN');
	} else {
		open($FILE, '<', "$filename") ||
			die "$P: $filename: open failed - $!\n";
	}
	undef $/;
	my $file = <$FILE>;
	close $FILE;

	my $spdx = "SPDX-License-Identifier:";

	$file =~ s/\b$spdx[ \t]*((?:\([ \t]*)*)GPL(\d\.\d)/$spdx \1GPL-\2/g;
	$file =~ s/\b$spdx[ \t]*((?:\([ \t]*)*)(L?GPL-\d\.\d)\+/$spdx \1\2-or-later/g;
	$file =~ s/\b$spdx[ \t]*((?:\([ \t]*)*)(L?GPL-\d\.\d)(?!-or-later|-only)/$spdx \1\2-only/g;

	while ($file =~ s/\b$spdx[ \t]($balanced_parens)(?![ \t]*AND|[ \t]*OR)/$spdx . ' ' . deparenthesize($1)/ex) {
		;
	}

	if ($filename eq '-') {
		open($FILE, '>&STDOUT');
	} else {
		open($FILE, '>', "$filename") ||
			die "$P: $filename: open failed - $!\n";
	}
	print $FILE $file;
	close $FILE;
}
EOF

git grep --name-only "$spdx" | \
    grep -vP "^(?:LICENSES/|Documentation/process/license-rules\.rst)" | \
    xargs perl $license_script

rm -f $license_script
