#!/usr/bin/perl

#------------------------------------------------------------------------------
# ALTERNATIVE APPROACH IS TO DELETE ALL ENTRIES IN SESSIONS TABLE + DIR AT 4AM
#------------------------------------------------------------------------------

use strict;
use warnings;

BEGIN {
    use FindBin qw($Bin); # warn $Bin;
    use lib (
        "$Bin/../../../lib",
        '/home/raj/perl5/lib/perl5',
    );
}

use Data::Dumper;
use LIMS::Local::Config;
use CGI::Session::ExpireSessions 1.08;

use constant DELTA => 24 * 60 * 60; # 1d in seconds
# use constant DELTA => 10; # use for testing -- expire sessions that haven't been accessed in 10 seconds

# print 'Removing sessions that are more than '.DELTA." seconds\n";

my $config = LIMS::Local::Config->instance(); # warn Dumper $config;

my $settings = $config->{settings}; # warn Dumper $settings;
my $path_to_app_root = $config->{path_to_app_root}; # warn Dumper $path_to_app_root;

my $opts = {
    cgi_session_dsn => { # match method in CGI_SESSION_OPTIONS
		db   => 'driver:mysql;serializer:'.$settings->{db_session_serializer}, 
		file => 'driver:File;serializer:' .$settings->{file_session_serializer}, 
    },
    dsn_args => {
        db => {
            DataSource  => 'dbi:mysql:database='.$settings->{production_db},
            User        => $settings->{db_user_id},
            Password    => $settings->{db_password},
        },
        file => {
            Directory => $path_to_app_root.'/sessions',
#           NoFlock   => '',
#           Umask     => '',
        }
    },
};

{ # expire sessions:
    my %args = ( delta => DELTA, verbose => 1 );
    my $expirer = CGI::Session::ExpireSessions->new(%args);

    $expirer->expire_sessions(
        cgi_session_dsn	=> $opts->{cgi_session_dsn}->{file},
        dsn_args		=> $opts->{dsn_args}->{file},
    );
    
    $expirer->expire_sessions(
        cgi_session_dsn	=> $opts->{cgi_session_dsn}->{db},
        dsn_args		=> $opts->{dsn_args}->{db},
    );
}

__END__
THESE DON'T WORK ANYMORE - REPLACED BY EXAMPLES FROM C::S::E DOCS
# database sessions table:
CGI::Session::ExpireSessions->new(
    delta           => $opts->{delta},
    verbose         => $opts->{verbose},
    dsn_args        => $opts->{dsn_args}->{db},
    cgi_session_dsn => $opts->{cgi_session_dsn}->{db},
)->expire_sessions;

# sessions directory:
CGI::Session::ExpireSessions->new(
    delta           => $opts->{delta},
    verbose         => $opts->{verbose},
    dsn_args        => $opts->{dsn_args}->{file},
    cgi_session_dsn => $opts->{cgi_session_dsn}->{file},
)->expire_sessions;