#!/usr/bin/perl -w

=head1 NAME

dh_perms - set some special permissions after dh_fixperms

=cut

use strict;
use Debian::Debhelper::Dh_Lib;

=head1 SYNOPSIS

B<dh_perms> [S<I<debhelper options>>]

=head1 DESCRIPTION

dh_perms is a debhelper program that is responsible for setting the
permissions of files and directories according to the information in 
debian/permissions. It is intended to be run after dh_fixperms.

The file debian/permissions is a tab seperated file where the first column 
contains a filename, the second one the permissions in octal format, the 
third one the owner and the fourth one the group. A dash in columns 2 to 4
means that this information will not be modified.

=head1 OPTIONS

=over 4

None except the standard debhelper options.

=back

=cut

init();

my %perms;
my %owners;
my %groups;

# TODO: There should be a way to change this by command-line
my $permfile = "debian/permissions";

open PERMFILE, $permfile or exit 0; #print "could not open permfile\n";
while (my $curline = <PERMFILE>)
{
	#NOTE: Broken lines are not always detected. (e.g. not defining anything valid)

	# remove lineend
	chomp($curline);
	# skip comments/empty lines
	next if $curline =~ /^#/ || $curline !~ /\S/;
	(my $filename, my $octmode, my $owner, my $group) = split (/\s+/, $curline);
	
	die qq{$0: could not accept "$curline": wrong octmode $octmode\n} unless $octmode =~ /^[0-7]{3,4}$/;
	$perms{$filename} = $octmode unless $octmode eq "-" or not defined $octmode;
	
	$owner = getpwnam($owner) if defined getpwnam($owner);
	$owners{$filename} = $owner unless $owner eq "-" or not defined $owner;
	
	$group = getgrnam($group) if defined getpwnam($group);
	$groups{$filename} = $group unless $group eq "-" or not defined $group;

}
close PERMFILE;	


foreach my $package (@{$dh{DOPACKAGES}}) {
	my $tmp=tmpdir($package);
	foreach my $file (keys %owners)
	{
		next unless -e $tmp.$file;
		chown $owners{$file}, -1, $tmp.$file or die "failed to chown $file";
		verbose_print "chowned file $file to $owners{$file}";
	}
	foreach my $file (keys %groups)
	{
		next unless -e $tmp.$file;
		chown -1, $groups{$file}, $tmp.$file or die "failed to chgrp $file";
		verbose_print "chgrped file $file to $groups{$file}";
	}
	foreach my $file (keys %perms)
	{
		next unless -e $tmp.$file;
		my $nummod = oct("0".$perms{$file});
		chmod $nummod, $tmp.$file or die "failed to chmod $file";
		verbose_print "chmoded file $file to ".sprintf("0%o", $nummod);
	}

}

=head1 SEE ALSO

L<debhelper(7)>

This program is not yet part of debhelper.

=head1 AUTHOR

Willi Mann <willi@wm1.at>

=cut

