Every once in a while, you'll realize you've got a corrupt or missing file, maybe caused by recovery from a failing hard drive, or an accidental deletion of something important.  If you're not sure what package the damaged file is from, then one way to solve this would be to force a reinstall of every currently installed package.

While technically, this could be done manually, but considering there are usually upwards of a couple of thousand packages installed, that could take quite a while.  There are a lot of postings around the Internet asking how to reinstall all packages on a Debian or Ubuntu Linux system, but no real answers that I've found as to how to do it in an automated manner; so, I wrote this little script to do it.

It's actually quite simple to do, but it can take a long time to run this script, as it reinstalls each package individually.  This isn't a problem, as there are no dependency issues, since all dependencies are already installed, even if some may be corrupt at the beginning of this process.  The last machine I ran this on, though (which, admittedly, was a 2.8 GHz Celeron with only 1 GB of RAM, so take that time with a grain of salt) took somewhere in the neighbourhood of 12 hours to completely download and reinstall a touch over 2300 packages. 

Save this code to a file called reinstall_all.pl, make it executable, and run it.  A few hours later, all your packages will have been reinstalled, so any file corruption should be eliminated.

The code:

#!/usr/bin/perl
$\="\n";
$packages_file = "/tmp/packages.txt";
system("dpkg --get-selections | grep -v deinstall > ".$packages_file);
open(my $fh, "<", $packages_file);
while(<$fh>)
{
@package = split /\s+/, $_;
print "Reinstalling package: ". $package[0];
system("apt-get install --reinstall ".$package[0]);
system("apt-get clean");
}
close $fh;

See?  Pretty simple.  Dump the current package list to a file, then read each line of that file, pull out the name of the package, and reinstall it using the standard system commands.

Hopefully this makes things a little easier for someone having issues with file corruption.

If it doesn't, you may have to add an extra system() call to do a dpkg-reconfigure just before the apt-get clean line, something like this:

system("dpkg-reconfigure ".$package[0]);

That will mean some prompts will come up during the process for any package that has configuration options, such as MySQL on Debian.  While it will slow things down a little, it's still much quicker than doing everything manually.