#!/usr/bin/perl

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

use strict;
use warnings;

use lib '/home/raj/perl5/lib/perl5';

use IO::All;
use DateTime;
use Config::Auto;
use Data::Dumper;
use Data::Printer;
use feature 'say';
use CGI::Session::ExpireSessions 1.08;

use FindBin qw($Bin); # warn $Bin;
use lib "$Bin/../../../lib";

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";

use vars qw($fh);
# open my $fh, '>', "$Bin/../../../logs/debug.txt"; # print $fh Dumper \@ARGV;

#-------------------------------------------------------------------------------
unless (@ARGV) { $ARGV[0] = 'leeds' }
#-------------------------------------------------------------------------------
# Dancer2 apps (yml file sessions):
my @D2_apps = ('NGS', 'RequestForm', 'DraftReporter');

# db sessions:
for my $centre (@ARGV) { # print $fh Dumper $centre;
	# can't do this in a loop - only loaded once !!
	# my $config = LIMS::Local::Config->instance(); # _debug($config);
	$ENV{CENTRE} = $centre; # load correct settings file

	my $src = "$Bin/../../../config/lims_config.pl"; # _debug($src);
	my $cfg = Config::Auto::parse($src, format => 'perl'); # _debug($cfg);
	my $settings = $cfg->{settings}; # _debug($settings);

	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 => $Bin.'/../../../sessions',
	#           NoFlock   => '',
	#           Umask     => '',
			}
		},
	}; _debug($opts);

	{ # 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},
		);
	}
}

my $epoch  = DateTime->now->epoch; # say $epoch; exit;
my $oneday = 24 * 3600; # seconds

# Dancer2 yml file sessions:
for my $app (@D2_apps) {
    my $io = io('/home/raj/apps/'.$app.'/sessions');
    my @contents = $io->all; # p @contents;
    for my $file (sort by_epoch @contents) { # p $_->ext;
        next unless $file->ext eq 'yml';
        my $age = $epoch - $file->mtime; # in seconds
        # say $file->file .
        #    ( $age > $oneday ? ' for deletion' : ' NOT for deletion' );
        # delete any >24 hrs old:
        io($file->file)->unlink if $age > $oneday;
    }
}

# temporary CGI session files, eg:
    # /tmp/cgisess_bdf4707b9625b6b686acb3becd20e571
    # /home/raj/CGISESSID 0914f56735493cb0ddc2f50489fb98f8
for my $dir ( '/tmp', '/home/raj' ) { # temp cgisess files:
	my $io = io($dir);
    my @contents = $io->all; # p @contents;
	for my $item (sort by_epoch @contents) { # p $item->type;
        next unless $item->type eq 'file'
            && $item->filename =~ /^cgisess(id\s|_)\w{32}$/i;
        my $age = $epoch - $item->mtime; # in seconds
        # say $item->file . " ($age sec) " .
        #    ( $age > $oneday ? 'for deletion' : 'NOT for deletion' );
        # delete any >24 hrs old:
        io($item->file)->unlink if $age > $oneday;
    }
}

sub by_epoch { $a->mtime <=> $b->mtime }
=begin
sub by_epoch {
	my $foo = $a;
	my $bar = $b; say "$foo->filename <=> $bar->filename";
	$foo->mtime <=> $bar->mtime; 
}
=cut
	
sub _debug {
	return unless $fh;
	print $fh Dumper @_;
}

__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;
