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

# Modules
use Zymonic::Config;
use Zymonic::DB;
use Zymonic::Table;
use Zymonic::Auth;

# Library path
BEGIN
{
    use vars qw($location $script_name $script_location $utils);
    use Zymonic::Utils qw(clean debug death_handler get_array);
    $main::SIG{__DIE__} = \&death_handler;
}

# Clean path
$ENV{PATH} = "/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/sbin:/bin:/usr/bin:/sbin:/usr/sbin";

my $system = clean( $ARGV[0], "_" );

debug("Zymonic starting... system: $system");
my $config = Zymonic::Config->new(
    system_name => $system,
    config_dir  => "/etc/zymonic",
    ip_address  => '127.0.0.1',
    protocol    => 'http'
);

my $db = Zymonic::DB->new( config => $config );

unless ( $db->isa('Zymonic::DB::Oracle') )
{
    print "Not an Oracle DB.\n";
    exit(1);
}

foreach my $table ( map { $config->get_def( 'Table', $_->{ZName}->{content} ) } get_array( $config->SysDef->{Table} ) )
{
    my $table_zname = $table->{ZName}->{content};
    my $table_name = ( ref( $table->{SQLName} ) eq 'HASH' ? $table->{SQLName}->{content} : $table->{ZName}->{content} );

    # always remove the zzluu update trigger
    my @triggers = ("${table_name}zzluu");

    # check for any auto increments and remove triggers for each
    foreach my $key ( get_array( $table->{Key} ) )
    {
        if ( ref( $key->{Autoincrement} ) && $key->{Autoincrement}->{content} eq 'true' )
        {
            push( @triggers, "${table_name}$key->{FieldName}->{content}t" );
        }
    }

    foreach my $trigger (@triggers)
    {
        eval { $db->run_statement( { string => "DROP TRIGGER $trigger", params => [] } ); }
          or do
        {
            my $exception = $@;
            if ( ref($exception) )
            {
                if (   $exception->isa('Zymonic::Exception::Db::Query_Run')
                    && $exception->{sql_err} !~ /(.*) does not exist/i )
                {
                    $exception->rethrow;
                }
            }
            else
            {
                if ( $exception !~ /(.*) does not exist/i )
                {
                    die $exception;
                }
            }
        };
    }
}
