#!/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 debug_exception);
    $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], "_" );
unless ($system)
{
    print "secure_all_unsecured.pl [system] [tables] [force (optional)]\n";
    print "\t tables can be: comma-separated list of znames\n";
    print "\t                * for all tables\n";
    print "\t                'record_based_only' for all tables with record permissions\n";
    exit(1);
}

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 && $table !~ /$search/ && $search ne 'record_based_only';

    eval {
        my $to = Zymonic::Table->new(
            table  => $table,
            zname  => $table,
            config => $config,
            auth   => $auth,
            db     => $db,
        );
        next if $search && $search eq 'record_based_only' && $to->{rp_dependencies} == 0;

        debug( "Securing table " . $table );

        $to->secure_unsecured( $ARGV[2] eq 'force' );
        1;
    } or do
    {
        debug_exception($@);
    };
}

debug("Finished securing tables.");
