#!/usr/bin/perl
################################################################################
#                                                                              #
#                                                                              #
# Copyright (C) 2006 Mandriva Linux                                            #
#                                                                              #
# Olivier Thauvin <nanardon@mandriva.org>                                      #
#                                                                              #
# This program is free software; you can redistribute it and/or modify         #
# it under the terms of the GNU General Public License Version 2 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.                                 #
#                                                                              #
# You should have received a copy of the GNU General Public License            #
# along with this program; if not, write to the Free Software                  #
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.   #
################################################################################

use strict;
use warnings;

use Config::IniFiles;
use Getopt::Long;

GetOptions(
    'add' => \my $add,
    'remove' => \my $remove,
    'file=s' => \my $filetomodify,
) or die "wrong usage\n";
my $pref = $ARGV[0] or die "wrong usage\n";


$filetomodify ||= '/etc/kderc';

my $ini = Config::IniFiles->new(
    (-r $filetomodify ? (-file => $filetomodify) : ()),
);

my @prefixes = grep { $_ } split(/,/, $ini->val('Directories-default', 'prefixes', ''));

$pref =~ s:/+$::; # removeing leading /

if ($add) {
    push(@prefixes, $pref);
} elsif ($remove) {
    @prefixes = grep { !m:^\Q$pref\E/*$: } @prefixes;
}

my @puniq;
my %uniq;
foreach (@prefixes) {
    #uniq
    next if ($uniq{$_});
    $uniq{$_} = 1;
    push(@puniq, $_);
}

@prefixes = @puniq;

if (@prefixes) {
    $ini->newval('Directories-default', 'prefixes', join(',', @prefixes));
} else {
    $ini->delval('Directories-default', 'prefixes');
}

$ini->WriteConfig($filetomodify);

