#!/usr/bin/perl

use strict;

use File::Spec;
use Config::Tiny;
use Data::Dumper;
use LIMS::Local::Utils;

my $path_to_app_root = LIMS::Local::Utils::find_home
    || die "Couldn't find path to application directory"; # warn $path_to_app_root;

# open my $fh, '>' . '/tmp/env.txt'; print $fh Dumper \%ENV;

my $config = Config::Tiny->new();

# $ENV{CENTRE} is set in init.d lims_fastcgi_* scripts but not crons or .t
$ENV{CENTRE} ||= 'leeds';

my $local = do {
    my $src = sprintf '%s/config/settings/%s.txt', $path_to_app_root, $ENV{CENTRE};
    $config->read($src) or die $Config::Tiny::errstr;
}; # warn Dumper $local;
my $global = do {
    my $src = sprintf '%s/config/settings/global.txt', $path_to_app_root;
    $config->read($src) or die $Config::Tiny::errstr; 
}; # warn Dumper $global;

my %settings = map %{ $local->{$_} }, qw(sys_admin local_admin); # warn Dumper \%settings;

# need to add $ENV{CENTRE} to settings as it's not visible to app (check not
# already set):
die "already have a settings entry for '_centre': $settings{_centre}"
    if $settings{_centre};
$settings{_centre} = $ENV{CENTRE};
$settings{yaml_dir} = '.' . $ENV{CENTRE}; 

# add global settings (check first no key name clashes with local settings):
do { # warn Dumper $_;
    die "$_ is already in use" if $settings{$_};
    $settings{$_} = $global->{_}->{$_};
} for keys %{ $global->{_} }; # warn Dumper \%settings;

my %dbh_params = (
    driver => 'mysql',
    userid => $settings{db_user_id},
    pwd    => $settings{db_password},
    db     => $settings{development_db}, # default to devel db - overridden in mod_perl config
);

my %cfg = (
    settings => \%settings,

#    authen_cfg => { } # doesn't work here if using instance(); see 'unused configs'
#    # block in __END__ for details; moved to LIMS::_configure_plugins()

    db => {
        development => $settings{development_db},
        production  => $settings{production_db},
    },

    dbh_params => [
		"dbi:$dbh_params{driver}:$dbh_params{db}",
		$dbh_params{userid},
		$dbh_params{pwd},
	],

	dfv_defaults => {
		missing_optional_valid => 1,
		filters => 'trim', # trims white space pre/post field param
		field_filters => { }, # use for forcing field formats eg foo => 'uc' 
		msgs => {
			any_errors 	=> 'dfv_errors', # default err__
			# invalid_separator => '<br />', # needs to be in own <td> to format OK
			prefix 		=> 'error_', # default err_
			invalid    	=> 'invalid', # default 'Invalid'
			missing 	=> 'missing', # already 'Missing'
			format 		=> '<span class="dfv_errors">&#171; %s</span>',
		},
	},

    path_to_app_root => $path_to_app_root,
	path_to_www_docs => $path_to_app_root . '/static/',

    session_config => {
        CGI_SESSION_OPTIONS => [], # defined in cgiapp_init
        DEFAULT_EXPIRY      => '24h', # for forgotten_password expiry
        SEND_COOKIE         => 1,
        COOKIE_PARAMS => {
            -path    => '/',
        },
    },

    session_options_file => {
        Directory => $path_to_app_root.'/sessions',
        IDFile    => $path_to_app_root.'/sessions/cgisession.id',
        IDInit    => 1000, # start at
        IDIncr    => 1, # increment by
    },

    tmpdir => File::Spec->tmpdir(),
    
    tt_config => {
        TEMPLATE_OPTIONS => {
            WRAPPER      => 'site/tt_wrapper',
            PRE_PROCESS  => 'site/tt_pre_process',
#			PRE_CHOMP    => 1, # screwing template format
			POST_CHOMP   => 1, 
			# need to sort dir permissions for mod_perl & server.pl:
#			COMPILE_DIR  => $path_to_app_root.'/compiled_tmpl',
            INCLUDE_PATH => [
                $path_to_app_root.'/src',
                $path_to_app_root.'/templates',
            ],
        },
    },
    # permissions that allow unlocking records:
    unlock_actions => [ qw(edit_pid modify_results report) ],
    
    use_cgi_ajax => 1,
);

return \%cfg;

__END__
# unused configs:
#    authz_cfg => { # CAP::Authorization config; see update_widget() in pod for eg of complex config
#		DRIVER => [ 'DBI',
#			TABLES => [ 'users u', 'user_functions f', 'user_permission p' ],
#			JOIN_ON => 'u.id = p.user_id AND p.function_id = f.id',
#			USERNAME => 'username',
#            CONSTRAINTS => {
#                function => '__PARAM_1__',
#				 # username => 'ADMIN', # need to make this an 'OR'
#            },
#		],
#       FORBIDDEN_RUNMODE => 'forbidden', # doesn't work as expected - using template->fill() method instead
#    },

#    dbi_driver => [ # using Generic driver now
#        'DBI',
#        DBH => undef, # defined in cgiapp_init()
#    	TABLE       => 'users',
#		CREDENTIALS => [ qw(authen_username authen_password) ], # default & correspond to login form field names
#		CONSTRAINTS => {
#            username => '__CREDENTIAL_1__',
#			active	 => 'yes',
#		},
#    	COLUMNS     => {
#    	    'sha1_base64:password' => '__CREDENTIAL_2__' # using SHA1
#    	},
#    ],

#    dbic_driver => [
#        'DBIC',
#        SCHEMA => undef, # defined in cgiapp_init() $c->param('schema'),
#        CLASS => 'Users', # = My::DBIC::Users
#        FIELD_METHODS => [ qw(username password) ], # qw(user MD5:passphrase)
#        CREDENTIALS => [ qw(authen_username authen_password) ],
#    ],

#    flash => [
#        session_key  => 'FLASH',
#        auto_cleanup => 1,
#    ],
=begin # doesn't work if using Class::Singleton instance() method of loading config
    authen_cfg => { # CAP::Authentication
        DRIVER => [ ], # defined in cgiapp_init()

        LOGIN_SESSION_TIMEOUT => {
		    IDLE_FOR => '24h', # same as session default - overridden under CUSTOM:
		    EVERY  => '1d',
		    CUSTOM => \&custom_timeout, # returns true if the session should be timed out
		},

        LOGIN_RUNMODE => 'login', # redirect_after_login requires destination field in .tt if used
#       LOGIN_URL     => '/hmds/login', #  causes redirection loop & don't need if using LOGIN_RUNMODE
#       POST_LOGIN_URL     => '', # leave these blank to re-direct to original requested page
#		POST_LOGIN_RUNMODE => '', # will override POST_LOGIN_URL

        STORE => 'Session', # ie CAP::Store::Session
#		STORE => [
#            'Cookie',
#            NAME   => 'HILISAuthentication',
#            SECRET => 'HILIS4',
#            EXPIRY => '30m',
#        ],
    },
=cut

