#!/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);
    $main::SIG{__DIE__} = \&death_handler;

    our %warnings = ();
    $SIG{__WARN__} = sub {
        my $warning = shift;
        $warnings{$warning} = 0 unless $warnings{$warning};
        $warnings{$warning}++;
    };
}

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

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

# enable cache for table includes and relationship permissions
# this will speed up any security changes done during config build
$Zymonic::object_cache = { 'Zymonic::TableInclude' => {}, 'Zymonic::RelationshipPermissions' => {}, };

my $config_file = clean( $ARGV[1], '\/_' ) || '';
my $skip_db_update = $ARGV[2] || '';

my $fh;
if ($config_file)
{
    open( $fh, ">", $config_file ) || die "Couldn't open config file";
    $|                         = 1;
    $Zymonic::Utils::debugfile = $fh;
}
else
{
    $Zymonic::Utils::debugs_written = 1;
}

$Zymonic::ZCONFIG{$Zymonic::system} = Zymonic::Config->new(
    system_name           => $Zymonic::system,
    config_dir            => "/etc/zymonic",
    ip_address            => '127.0.0.1',
    protocol              => 'http',
    build_cache           => 'Y',
    skip_db_update        => ( $skip_db_update ? 'Y' : '' ),
    build_progress_output => 'Y',
);

print "$Zymonic::system cache successfully built.\n";

# for zcps version

print "Zymonic Version: Setting zcps version for $Zymonic::system";

my @files         = grep { -f $_ && readlink($_) =~ /zcps/ } glob "/etc/zymonic/$Zymonic::system/*";
my $zcps_file     = readlink( $files[0] );
my $info_revision = `svn info $zcps_file | grep "Revision: "`;
my $info_url      = `svn info $zcps_file | grep "URL: "`;
my $zcps_version  = substr( $info_revision, 10 );
chomp $zcps_version;
my $zymonic_type = 'U';
if ( $info_url =~ /trunk/ )
{
    $zymonic_type = 'D';
}
elsif ( $info_url =~ /qa/ )
{
    $zymonic_type = 'Q';
}
elsif ( $info_url =~ /live/ )
{
    $zymonic_type = 'L';
}
$Zymonic::ZCONFIG{$Zymonic::system}->set_version_number( undef, 'C' . $zymonic_type . $zcps_version );

print "\nWARNINGS:\n" . join( "\n", map { $_ . " WAS REPEATED $warnings{$_} TIMES" } keys(%warnings) ) . "\n";
