#!/usr/bin/env perl
use strict;
use warnings;
use Time::HiRes qw(time);
use POSIX       qw(strftime);
use Parallel::ForkManager;
use Sys::Syslog qw(:standard :macros);
use Getopt::Long;

my ( $DRYRUN, $VERBOSE ) = ( 0, 0 );
Getopt::Long::Configure("bundling");
GetOptions( "dry-run" => \$DRYRUN, "verbose|v" => \$VERBOSE )
  or die "Usage: $0 [--dry-run] [--verbose|-v]\n";

my $CLEAN = $DRYRUN ? 0 : 1;    # Default: clean, unless --dry-run is specified

my $pm = Parallel::ForkManager->new(4);
openlog( 'alt-php-gc', 'pid', LOG_DAEMON );

# ------------------------------------------------------------
# Find all alt-* PHP SCL collections
# ------------------------------------------------------------
my @collections = grep { /^alt-/ } split /\n/, qx{scl list-collections 2>/dev/null};

foreach my $collection (@collections) {
    $pm->start and next;

    print "processing=$collection\n" if $VERBOSE;

    # Get PHP session settings
    my $gc_maxlifetime = qx{scl run $collection -- php -r "echo ini_get('session.gc_maxlifetime');" 2>/dev/null};
    my $save_path      = qx{scl run $collection -- php -r "echo ini_get('session.save_path');" 2>/dev/null};
    chomp( $gc_maxlifetime, $save_path );

    # Whitelist: only allow expected alt-php session dirs
    my @allowed_paths = (qr{^/opt/alt/php\d+/var/lib/php/session/?$});
    unless ( $save_path && grep { $save_path =~ $_ } @allowed_paths ) {
        syslog( LOG_WARNING, "%s: rejecting save_path=%s (not in whitelist)", $collection, $save_path // 'undef' );
        print "rejecting save_path=$save_path (not in whitelist)\n" if $VERBOSE;
        $pm->finish;
    }

    unless ( $gc_maxlifetime && -d $save_path ) {
        syslog( LOG_WARNING, "%s: invalid config (gc_maxlifetime=%s, save_path=%s)", $collection, $gc_maxlifetime // '?', $save_path // '?' );
        $pm->finish;
    }

    # Threshold in seconds
    my $threshold     = time - $gc_maxlifetime;
    my $threshold_str = strftime( "%Y-%m-%d %H:%M:%S", localtime($threshold) );

    print "path=$save_path threshold_secs=$gc_maxlifetime threshold_time=$threshold_str\n" if $VERBOSE;

    my ( $scanned, $expired, $deleted ) = ( 0, 0, 0 );

    opendir( my $dh, $save_path ) or do {
        syslog( LOG_WARNING, "%s: cannot open %s: %s", $collection, $save_path, $! );
        $pm->finish;
    };

    while ( my $file = readdir($dh) ) {
        next unless $file =~ /^sess_/;
        my $full = "$save_path/$file";

        # ---- Symlink safety ----
        next if -l $full;    # skip symlinks entirely
        next unless -f _;    # only process regular files
                             # ------------------------

        my $mtime        = ( stat(_) )[9] // next;
        my $age          = time - $mtime;
        my $expired_flag = ( $mtime < $threshold ) ? 1 : 0;

        if ($VERBOSE) {
            my $mtime_str = strftime( "%Y-%m-%d %H:%M:%S", localtime($mtime) );
            printf "age=%ds mtime=%s expired=%s file=%s\n", $age, $mtime_str, ( $expired_flag ? '1' : '0' ), $full;
        }

        $scanned++;
        next unless $expired_flag;

        $expired++;
        if ($CLEAN) {
            unlink $full and $deleted++;
        }
    }
    closedir($dh);

    syslog( LOG_INFO, "%s: %s %d expired of %d files (threshold=%ds)", $collection, ( $CLEAN ? "deleted" : "would delete" ), ( $CLEAN ? $deleted : $expired ), $scanned, $gc_maxlifetime );

    print "summary collection=$collection scanned=$scanned expired=$expired deleted=$deleted\n" if $VERBOSE;
    $pm->finish;
}

$pm->wait_all_children;
closelog();
exit 0;
