#!/usr/bin/perl

# Copyright © 2011 Jakub Wilk <jwilk@debian.org>
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

=head1 NAME

dh_buildid - move /usr/lib/debug/* files into build-id locations

=cut

use strict;
use warnings;

use File::Find;
use Debian::Debhelper::Dh_Lib;

=head1 SYNOPSIS

B<dh_buildid> [S<I<debhelper options>>] [B<-X>I<item>]

=cut

init();

umask 0022;
foreach my $package (@{$dh{DOPACKAGES}}) {
    my $debug_root = tmpdir($package) . "/usr/lib/debug";
    my $build_id_root = "$debug_root/.build-id";
    next unless -d $debug_root;
    my $wanted = sub {
        return unless -f $_;
        return if excludefile($_);
        my $path = $_;
        my $elfnotes = `readelf -n $path`;
        my ($build_id_dir, $build_id_path);
        if ($elfnotes=~/^\s+Build ID: ([0-9a-f]{2})([0-9a-f]+)$/m) {
            $build_id_dir = "$build_id_root/$1";
            $build_id_path = "$build_id_dir/$2.debug"
        } else {
            # Maybe built with old GCC? Or readelf is too old? Or it's not an ELF
            # at all? Anyway, leaving it as it won't hurt.
            return;
        }
        doit('mkdir', '-p', $build_id_dir)
            unless -d $build_id_dir;
        doit('mv', $path, $build_id_path);
    };
    find({wanted => $wanted, no_chdir => 1}, $debug_root);
    # Pure empty directories:
    doit('find', $debug_root, '-type', 'd', '-empty', '-delete');
}

=head1 SEE ALSO

L<debhelper(7)>

=head1 AUTHOR

Jakub Wilk <jwilk@debian.org>

=cut

# vim:ts=4 sw=4 et
