#!/bin/bash
#
# This script is free software; you can redistribute it and/or modify it
# under the terms of version 2 of the GNU General Public License as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
# more details.
#
# Copyright 2010 Canonical Limited
#
cd `dirname "$0"`

for i in nouveau/Makefile nouveau/ttm/Makefile nouveau/nouveau/Makefile
do
	perl -e '
		while (<>) {
			$_ =~ s/^(drm-y\s*:=)/$1 list_sort.o /;
			$_ =~ s/^(nouveau|drm|drm_kms_helper|ttm)-/lbm_$1-/;
			$_ =~ s/ccflags-y := .*$/ccflags-y := -I\$(M)\/nouveau\/include\/drm -I\$(src)\/include/;

			if (/^obj-(y|[^\s]*\))/) {
				if ($1 eq '"'"'$(CONFIG_COMPAT)'"'"' ||
				    $1 eq '"'"'$(CONFIG_DRM_KMS_HELPER)'"'"' ||
				    $1 eq '"'"'$(CONFIG_DRM)'"'"' ||
				    $1 eq '"'"'$(CONFIG_DRM_TTM)'"'"' ||
				    $1 eq '"'"'$(CONFIG_DRM_NOUVEAU)'"'"') {
					if ($_ =~ /\.o\s*$/) {
						$_ =~ s/(=\s+)/$1lbm_/g;
					}
					$_ =~ s/-\$\(CONFIG_DRM_NOUVEAU\)/-m/;
					print;
				}
			} else {
				print;
			}
		}
	' <$i > $i.NEW
	mv $i.NEW $i
done

perl -e '
	@cvt = ();
	for $file (@ARGV) {
		open(FILE, "<$file") || die "$P: open failed - $!\n";
		while (<FILE>) {
			if (/EXPORT_SYMBOL.*\((\S+)\)/) {
				push(@cvt, $1);
			}
		}
		close(FILE);
	}
	$pat = join("|", @cvt);

	for $file (@ARGV) {
		print "FILE: $file\n";
		open(OUT, ">$file.NEW") || die "$P: open failed - $!\n";
		open(FILE, "<$file") || die "$P: open failed - $!\n";
		while (<FILE>) {
			if ($_ !~ /^\s*#\s*include/) {
				$_ =~ s/\b($pat)\b/lbm_$1/g;
			}
			#$_ =~ s/register_chrdev\(DRM_MAJOR,/register_chrdev(0,/;
			$_ =~ s/#define\s+DRM_MAJOR.*/#define DRM_MAJOR 227/;
			$_ =~ s/"drm"/"lbm-drm"/g;
			$_ =~ s/"dri"/"lbm-dri"/g;
			print OUT $_;
		}
		close(FILE);
		close(OUT);

		rename "$file.NEW", $file;
	}
' `find nouveau -name \*.[hc] -print`
