#!/usr/bin/perl
################################################################################
#    Copyright (C) 2009 by Eric Gerbier
#    Bug reports to: gerbier@users.sourceforge.net
#
#    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.
#
################################################################################
# sort une liste triee des regles les plus utilisiées
use strict;
use warnings;
use Getopt::Long;

sub help() {
	print "$0 donne une liste des regles triee par nombre d'utilisation\n";
	print "  -?/--help : cette aide\n";
	print "  -t/--top x : affiche le top x des domaines\n";
	print "  -n x : affiche les domaines ayant plus de x regles\n";
	print "  -e/--exclude motif : exclusion\n";
	exit;
}

my $opt_help;
my $opt_top;
my $opt_min;
my $opt_exclude;
Getopt::Long::Configure('no_ignore_case');
if (
	!GetOptions(
		'help|?'      => \$opt_help,
		'top|t=i'     => \$opt_top,
		'n=i'         => \$opt_min,
		'exclude|e=s' => \$opt_exclude,
	)
  )
{
	help();
}

if ($opt_help) {
	help();
}

my $min = $opt_min || 500;    # default

my $fic = '/etc/ccs/domain_policy.conf';

# sauvegarde des regles depuis la memoire vers les fichier
system '/usr/sbin/ccs-savepolicy';

my %base;

if ( open my $fh, '<', $fic ) {
	print "lecture\n";
	while ( my $line = <$fh> ) {
		chomp $line;
		if ( $line =~ m/^<kernel> (.*)/ ) {
		}
		elsif ( $line =~ m/^$/ ) {
		}
		elsif ( $line =~ m/^use_profile/ ) {
		}
		elsif ( $line =~ m/^allow_capability/ ) {
		}
		elsif ( ($opt_exclude) && ( $line =~ m/$opt_exclude/ ) ) {
		}
		else {
			$base{$line}++;
		}
	}
	close $fh;

	if ($opt_top) {

		# affiche le top "min" des regles
		print "top $opt_top des regles\n";
		my $i = 0;
	  LOOP1:
		foreach my $key ( reverse sort { $base{$a} <=> $base{$b} } keys %base )
		{
			print "$base{$key} : $key\n";
			$i++;
			last LOOP1 if ( $i > $opt_top );
		}
	}
	else {

		# affiche toutes les programmes contenant plus de min regles
		print "regles apparaissant plus de $min fois\n";
		my $i = 0;
		foreach my $key ( sort { $base{$a} <=> $base{$b} } keys %base ) {
			if ( $base{$key} > $min ) {
				print "$base{$key} : $key\n";
				$i++;
			}
		}
		print "total : $i\n";
	}
}
else {
	die "can not open $fic : $!\n";
}
