#! /usr/bin/perl

# strip all ELF binaries & shared libs in a directory (recursive)

while($ARGV[0] eq '-v') {
  shift;
  $verbose++;
}

$total = 0;
$saved = 0;

for $dir (@ARGV) {
  for $f (`find $dir -type f`) {
    chomp $f;
    next if $f =~ /modules/ && $f !~ /X11R6\/lib\/modules/;	# skip modules
    next if $f =~ /\.uc$/;					# skip some X.org modules
    next if $f =~ m#usr/lib/debug/#;				# skip debuginfo
    next if $f =~ m#/lib(ssl|crypto)\.so\.[\.\d]*$#;		# skip ssl libs
    $f0 = $f;
    $f =~ s/'/'\\''/g;
    $_ = `file '$f'`;
    $s = undef;
    if(/\sELF\s.*\s(shared\s+object|executable)/) {
      $s = "strip -s -R .note -R .comment '$f'";
    }
    elsif(/\sELF\s.*\srelocatable,|current ar archive/) {
      $s = "strip -g -R .note -R .comment '$f'";
    }
    if($s) {
      if($verbose) {
        print "$f0\n" if $verbose > 1;
        $old = -s $f0;
      }
      system $s;
      if($verbose) {
        $new = -s $f0;
        $saved += $old - $new;
        $total += $new;
      }
    }
  }
}

if($verbose) {
  if($total) {
    $per = sprintf "%.2f", $total / ($saved + $total) * 100;
  }
  else {
    $per = "100.00";
  }
  print "$saved bytes saved (new total size $total bytes [$per%])\n";
}

