#!/usr/bin/perl

# Copyright (C) 2010 Modestas Vainius <modax@debian.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# 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.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>

use strict;
use warnings;

use Dpkg;

use constant DATADIR => '/usr/share/pkg-kde-tools';

sub find_dpkg_gensymbols {
    my $dir;
    if ($0 =~ m@^(.+)/[^/]+$@) {
	$dir = $1;
    }
    unless ($dir && -f "$dir/dpkg-gensymbols.pl" &&
	-f "$dir/Dpkg/Shlibs/SymbolFile.pm") {
	$dir = DATADIR;
    }

    if (-f "$dir/dpkg-gensymbols.pl") {
	return ("$dir/dpkg-gensymbols.pl", $dir);
    }
    return (undef, undef);
}

my $old_symbolfile_load;

sub new_symbolfile_load {
    # Use Debian::PkgKde::SymbolsHelper::Symbol as base symbol
    my ($self, $file, $seen, $obj_ref, $base_symbol) = @_;
    unless (defined $base_symbol) {
	$base_symbol = 'Debian::PkgKde::SymbolsHelper::Symbol';
    }
    return &$old_symbolfile_load($self, $file, $seen, $obj_ref, $base_symbol);
}

sub check_dpkg_version {
    my @need = @_;
    my @ver = split(/[.]/, $Dpkg::version);
    my $ok = 0;
    for (my $i = 0; ! $ok && $i < @need && $i < @ver; $i++) {
	if ($ver[$i] > $need[$i]) {
	    $ok = 1;
	} elsif ($ver[$i] == $need[$i]) {
	    if ($i == $#need) {
		$ok = 1;
	    }
	} else {
	    # Less
	    last;
	}
    }
    return $ok;
}

if (check_dpkg_version(1, 15, 5)) {
    # Finally, run stock dpkg-gensymbols
    my ($exe, $dir) = find_dpkg_gensymbols();

    if (defined $exe) {
	if (defined $dir && $dir eq DATADIR) {
	    unshift @INC, DATADIR;
	}

	eval "use Dpkg::Shlibs::SymbolFile";
	eval "use Debian::PkgKde::SymbolsHelper::Symbol";

	# Replace Dpkg::Shlibs::SymbolFile::load with a custom version
	# which uses Debian::PkgKde::SymbolsHelper::Symbol rather than
	# Dpkg::Shlibs::Symbol
	$old_symbolfile_load = *Dpkg::Shlibs::SymbolFile::load;
	*Dpkg::Shlibs::SymbolFile::load = *new_symbolfile_load;

	do "$exe";
    } else {
	print STDERR "pkgkde-gensymbols: unable to determine execution context.", "\n";
	exit 1;
    }
} else {
    exec '/usr/bin/dpkg-gensymbols', @ARGV;
}
