#!/usr/bin/perl -w
use strict;

# purge_ld_conf.pl - remove spurious entry from /usr/lib/ocaml/ld.conf
# Copyright (C) 2002  Stefano Zacchiroli <zack@cs.unibo.it>
# 
# 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.
# 
# 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

my $ld_conf = "/usr/lib/ocaml/ld.conf";
my $var_ld_conf = "/var/lib/ocaml/ld.conf";
my %owners;

open(VAR_LD_CONF, "< $var_ld_conf") ||
  die "Can't open $var_ld_conf for reading\n";
while(<VAR_LD_CONF>) {
  next if (/^#/ or /^\s*$/);
  my ($dir, $cmd, $pkg) = split /\s+/;
  $owners{$dir} = $pkg;
}
close(VAR_LD_CONF);

sub is_spurious($) {
  my ($entry) = @_;
  $entry =~ s/\/?\s*$//;  # remove trailing "/" and spaces, if any
  my @sos = glob "$entry/*.{so,dll}";
  return($#sos == -1); # no dll found
}

sub purge_entry($) {
  my ($entry) = @_;
  my $pkg = $owners{$entry} || die "($owners{$entry}) Can't find pkg owning '$entry'\n";
  system("/usr/bin/ocaml-ldconf -p $pkg -r $entry");
}

open(LD_CONF, "< $ld_conf") || die "Can't open $ld_conf for reading.\n";
while(<LD_CONF>) {
  chomp;
  next if (/^#/ or /^\s*$/);  # skip comments and blank lines
  next if (/\/usr\/lib\/ocaml\/stublibs/);  # skip system paths
  next if (/\/usr\/local\/lib\/ocaml\/[^\d\.]+\/stublibs/); # skip local paths
  purge_entry($_) if is_spurious($_);
}
close(LD_CONF);

