#!/usr/bin/perl -w
#
# Alternatives wrapper script to enable user configurability
# Copyright (c) 2000 Anthony Towns
#
# 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 2 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.

use strict;

my $x = basename($0);
my $pref = $ENV{"ALT_$x"} || undef;

my $use = undef;
my $usepri = undef;

open ALT, "/var/lib/dpkg/alternatives/$x" or die "No such alternative\n";

my $line;
my $extra = 0;

$line = <ALT>;	# the first line is `auto' or `manual'
$line = <ALT>;	# next is the official link
# the lots of two lines: extra name, extra link; then a blank
while($line = <ALT>) {
	last if ($line =~ m/^\s$/);
	$line = <ALT>;
	$extra++;
}

while($line = <ALT>) {
	last if ($line =~ m/^\s*$/);

	my $pri = <ALT>;
	foreach my $i (1..$extra) { my $e = <ALT>; }

	chomp($line);
	chomp($pri);

	if (defined $pref) {
		next unless ($line =~ m/$pref/);
	}

	if (defined $use) {
		next if ($usepri > $pri);
	}

	$use = $line;
	$usepri = $pri;
}

if (!defined $use) {
	die "Couldn't find an acceptable alternative!\n";
}

exec($use, @ARGV);
die "Couldn't exec $use.\n";

sub basename {
	my $f = shift;
	$f =~ s,^.*/,,;
	return $f;
}
