#!/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;

    my $fh;
    open $fh, ">&STDERR";

    #open $fh, ">/tmp/resecure.log";
    $Zymonic::Utils::debugfile = $fh;

}

# 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 );

my $auth = Zymonic::Auth->new(
    config      => $config,
    session     => undef,
    DB          => $db,
    credentials => '',
    ip_address  => $config->ip_address
);

$auth->initialise;

foreach my $table (
    map { $_->{ZName}->{content} } grep { ref( $_->{RelationshipPermissions} ) }
    map { $config->get_def( 'Table', $_->{ZName}->{content} ) } get_array( $config->SysDef->{Table} )
  )
{

    my $search = $ARGV[1];
    $search =~ s/,/|/g;
    next if $search and $table !~ /$search/;

    my $to = Zymonic::Table->new(
        table  => $table,
        zname  => $table,
        config => $config,
        auth   => $auth,
        db     => $db,
    );

    debug( "Securing table " . $table );

    if ( $ARGV[2] eq 'force' )
    {
        $db->run_query(
            {
                string => 'UPDATE ' . $to->{tablename} . ' SET sec_id = NULL',
                params => [],
            }
        );
    }

    $to->secure_unsecured;
}
