#!/usr/bin/perl -w
###############################################################################
#    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
###############################################################################
# 2004 by Marcus Thiesen (marcus@thiesen.org)
# Check files which are in the system but not mentioned in the packages
# Version 0.01 (This is messy alpha code)
###############################################################################

use strict;
use warnings;

use File::Find;

my $infodir = "/var/lib/dpkg/info";
my @searchdirs = ("/bin", "/lib","/sbin", "/usr" ); # where to find files

print "Reading info dir...\n";
opendir DIR, $infodir or die "Couldn't open dir $infodir: $!\n";
my @files = grep /\.list/, readdir DIR;
closedir DIR;

print "Finished (" . int(@files) . " packages found)\n";
print "Building package file tree....\n";

my %data;
my $i = 0;
foreach my $infofile (@files) {
	open my $fh, "<$infodir/$infofile" or die "Couldn't open $infodir/$infofile for reading $!\n";	
	$infofile =~ /([^.]+)\.list/;
	my $pkgname = $1;
	foreach my $line (<$fh>) {
		chomp $line;
		$data{$line} = $pkgname;
	}
	$i++;
	syswrite(STDOUT,"\r$i");
	close $fh;
}
print "\nFinished\n";

print "Building local file tree....\n";
my %localdata;
find(sub { $localdata{$File::Find::name}++ }, @searchdirs ); 
print "Finished\n";

my @orphaned;
foreach my $file (keys %localdata) {
	push @orphaned, $file unless $data{$file};
}
@orphaned = grep {!m|^/usr/src|} @orphaned;

print "Orphaned files:\n";
print join "\n", sort grep {!m|^/lib/modules|}  @orphaned;
print "\n";