#!/usr/bin/perl

=head1 NAME

rtx-validator - Script that allow validate rt database

=head1 SYNOPSIS

rtx-validator -o Ticket --id 100

=cut

use strict;
use Getopt::Simple;

use lib qw(/opt/rt3/local/lib /opt/rt3/lib);

use RTx::Shredder;
use RTx::Shredder::Constants;
RTx::Shredder::Init();

=head1 DESCRIPTION

=head2 OPTIONS

=head3 -o, --object

Object(class) name that should be validated. Is case sensetive.

=head3 --id

Optional argument object ID.
If option is skipped then all objects of that class would be validated.

=cut

sub GetOptions
{
        my $desc = {
# Object name, case sensetive
                object => {
                        type => '=s',
                        env => '-',
                        verbose => 'Object name',
                },
# ID
                id => {
                        type => '=i',
                        env => '-',
                        verbose => 'ID',
                },
        };

        my $options = new Getopt::Simple;

        unless ( $options->getOptions( $desc, "Usage: $0 [options]" ) ) {
                die 'Options parsing error';       # Failure.
        }

        return $options;
}

my $opt = GetOptions();

unless( $opt->{'switch'}{'object'} ) {
	Usage();
	exit 0;
}

my $class = "RT::". $opt->{'switch'}{'object'};
eval "require $class;";
if( $@ ) {
	die "$@";
}

my $object = $class->new( $RT::SystemUser );

unless( $opt->{'switch'}{'id'} ) {
	Usage();
	exit 0;
}
$object->LoadById( $opt->{'switch'}{'id'} );
unless( $object->id ) {
	print "Can't load object with id ". $opt->{'switch'}{'id'} ."\n";
	exit 1;
}

my $shredder = RTx::Shredder->new;
$object->ValidateRelations( Shredder => $shredder );

foreach my $record( values %{ $shredder->{'Cache'} } ) {
	next unless( $record->{'State'} & INVALID );
	print STDERR $record->{'Object'}->_AsString ." is invalid\n";
	print STDERR "\t". (ref($record->{'Description'}) ?
			join( "\n\t", @{$record->{'Description'}} ) :
			$record->{'Description'})
		."\n";
}

#use Data::Dumper;
#print Dumper( $shredder );



sub Usage
{
	print <<END;
	Usage: $0 -o <ObjectName> --id <ObjectID>

END
	return 1;
}

=head1 SEE ALSO

RTx::Shredder.

=cut
