#!/usr/bin/perl -w

#----------------------------------------------------------------------
# copyright (C) 2006 Gordon Rowell <gordonr@gormand.com.au>
#
# 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;
use warnings;

use RPM2;
use File::Find;
use File::Path;
use File::stat;

# Files not owned by RPMs
# Files modified since install by RPM
# Templates from "non-standard" RPMs
# Templates overridden in templates-custom

use RPM2;
my $rpm2 = RPM2->open_rpm_db();

for my $dir ( qw(templates templates-user) )
{
    find({ wanted => \&custom_templates }, "/etc/e-smith/$dir-custom");

    find({ wanted => \&templates }, "/etc/e-smith/$dir");
}

sub custom_templates
{
    return unless -f;

    my $template = $File::Find::name;
    $template =~ s/-custom//;

    my $status = rpm_status(name => $File::Find::name);

    print "$File::Find::name: $status, " .
        ((-e $template) ? "OVERRIDE" : "ADDITION"), "\n";

}

sub templates
{
    return unless -f;

    my $template = $File::Find::name;

    my $status = rpm_status(name => $File::Find::name);

    return if ( $status eq "OWNED_BY_RPM");

    print "$File::Find::name: $status\n";
}

sub rpm_status
{
    my (%options) = @_;

    my @rpms = $rpm2->find_by_file($options{name});

    return "MANUALLY_ADDED" unless (@rpms);

    return "MULTIPLE_RPM_OWNERS " . join(", ", map { $_->as_nvre } @rpms)
	if (@rpms >= 2);

    my $install_time = $rpms[0]->tag("INSTALLTIME");

    my $st = stat($options{name}) or die "Couldn't stat $options{name}: $!";

    return "MODIFIED " . $rpms[0]->as_nvre if ($st->mtime > $install_time);

    return "OWNED_BY_RPM";
}
