#!/usr/bin/perl -w
#
# Copyright 2004 by Willi Mann <willi@wm1.at>
#
# 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.



use strict;

while (my $line = <STDIN>)
{
	if (( my $file, my $perms, my $user, my $group, my $type) = 
		( $line =~ /^([^\s]+)\s([^\s]+)\s([^\s]+)\s([^\s]+)(:?\s([^\s]+)|)/ ))
	{
		my $isdir = 0;
		my $isexecbyuser = 0;
		my $isexecbyother = 0;
		my $issymlink = 0;
		my $issetuid = 0;
		my $issetgid = 0;
		my $isreadablebyother = 0;
		my $pathtofile = $file;
		$pathtofile =~ s/^.*\/debian\/tmp//;

		#remove .dist from some config-files
		$pathtofile =~ s/\.dist$//;
		$perms = oct($perms);
		$isdir = 1 if -d $file;
		$isexecbyuser = 1 if $perms & 0100;
		$isexecbyother = 1 if $perms & 0001;
		$isreadablebyother = 1 if $perms & 0004;
		$issymlink = 1 if -l $file;
		$issetgid = 1 if $perms & 02000;
		$issetuid = 1 if $perms & 04000;

		
		if( $issymlink) 
		{
			# do nothing 
			$perms = "-";
			$user = "-";
			$group = "-";
		}
		#Deal with directories
		elsif( $isdir )
		{
			if (not $pathtofile =~ /\/usr/ )
			{
				#trust
			}
			else
			{
				# change to 755 root:root (dh_fixperms ?)
				$perms = 0755;
				$user = "root";
				$group = "root";
			}
		}
		#Now non-exec files
		elsif ( not $isexecbyuser )
		{
			if ( $pathtofile =~ /\/usr/ )
			{
				#change to 644 root:root (dh_fixperms ?)
				$perms = 0644;
				$user = "root";
				$group = "root";
			}
			else 
			{
				if ( $isreadablebyother )
				{	
					#set to 644 root:root 
					$perms = 0644;
					$user = "root";
					$group = "root";
				}
				else
				{
					#trust
				}
			}
		}
		#Now with executeables
		else
		{
			if ( $issetuid )
			{
				if ( $isexecbyother )
				{
					# set to 4755, trust for owner:group
					$perms = 04755;
				}
				else
				{
					# set to 4754, trust for owner:group
					$perms = 04754;
				}
			}
			elsif ( $issetgid ) {
				if ($isexecbyother) {
					# set to 2755, trust for owner:group
					$perms = 02755;
				} else {
					# set to 2754, trust for owner:group
				}
			}
			else 
			{	
				# set to 755 root:root
				$perms = 0755;
				$user = "root";
				$group = "root";
			}
		}
		next if $perms eq "-" and $user eq "-" and $group eq "-";
		printf "%s %o %s %s\n", $pathtofile, $perms, $user, $group;
		
	}
}
