#!/usr/bin/perl -w 
#
# Zymonic Business Process and Information Management System
# Copyright Zednax Limited 2008 -
# For Authors and Changelog see the subversion history

BEGIN
{
    use Zymonic::Utils qw(death_handler clean get_array);
    $main::SIG{__DIE__} = \&death_handler;
}

use Zymonic::Config;
use Zymonic;
$Zymonic::system  = '';
$Zymonic::session = '';

use Data::Dumper;
use Term::ReadKey;

$Zymonic::system = clean( $ARGV[0], '_' );
my $user = clean( $ARGV[1], '_,' );
my $password;
my $tables                     = clean( $ARGV[2], '_,*' );
my $orphan_record_action       = clean( $ARGV[3] );
my $remove_autocreated_records = clean( $ARGV[4] );
my $remove_deleted_records     = clean( $ARGV[5] );
unless ( $Zymonic::system && $user && $tables )
{
    print "perl zymonic_db_cleaner.pl [system] [user] [tables] [or] [rm ac] [rn d]\n"
      . "\t[tables]:\tcomma separated list of table znames to work on, or * for all\n"
      . "\t[or]:    \torphan record action -      \ti (ignore), d (delete), m (mark as deleted), n (create new parent)\n"
      . "\t[rm ac]:\tremove autocreated records -\ty/n\n"
      . "\t[rm d]: \tremove deleted records -    \ty/n\n";
    exit(1);
}

# get user password, set read mode as no echo
print "Enter Password for $user: ";
ReadMode('noecho');
$password = <STDIN>;
chomp($password);
print "\n";
ReadMode(0);

# setup the field factory
$Zymonic::field_factory = Zymonic::FieldFactory->new();

$Zymonic::ZCONFIG{$Zymonic::system} = Zymonic::Config->new(
    system_name => $Zymonic::system,
    config_dir  => "/etc/zymonic",
    ip_address  => '127.0.0.1',
    protocol    => 'http'
);
my $db = Zymonic::DB->new( config => $Zymonic::ZCONFIG{$Zymonic::system} );
my $auth = Zymonic::Auth->new(
    config     => $Zymonic::ZCONFIG{$Zymonic::system},
    session    => undef,
    DB         => $db,
    ip_address => $Zymonic::ZCONFIG{$Zymonic::system}->ip_address,
);
$db->{auth} = $auth;

# do inline auth
my $auth_result = $auth->inline_auth( '', { username => $user, password => $password } );

# error if inline auth failed
unless ( $auth_result && $auth_result->{result} eq 'PASS' )
{
    print "Authentication Failed: " . Dumper($auth_result);
    exit(1);
}

print "Cleaning DB for $Zymonic::system.\n";

my $all_tables = ( $tables eq '*' ? 'true' : '' );
my $tables_to_use = { map { $_ => 1 } split( ',', $tables ) };

# iterate through tables
foreach my $table (
    map { $Zymonic::ZCONFIG{$Zymonic::system}->get_def( 'Table', $_->{ZName}->{content} ) }
    grep { $tables_to_use->{ $_->{ZName}->{content} } || $all_tables }
    get_array( $Zymonic::ZCONFIG{$Zymonic::system}->SysDef->{Table} )
  )
{
    print "Cleaning $table->{ZName}->{content}.\n";
    if ( $orphan_record_action && $orphan_record_action !~ /i/i )
    {
        print "\tCleaning orphan records ($orphan_record_action).\n";
        $db->remove_orphan_records( $table, $orphan_record_action );
    }

    if ( $remove_autocreated_records && $remove_autocreated_records =~ /y/i )
    {
        print "\tRemoving autocreated records.\n";
        $db->remove_autocreated_records($table);
    }

    if ( $remove_deleted_records && $remove_deleted_records =~ /y/i )
    {
        print "\tRemoving deleted records.\n";
        $db->remove_deleted_records($table);
    }

}

print "Done.\n"

