#!/usr/bin/perl
#############################################################################
#
# rx_* dispatcher and handlers for VFU File Manager
# Copyright (c) 2002-2020 Vladi Belperchinov-Shabanski "Cade" 
# <cade@biscom.net> <cade.datamax.bg> http://cade.webbg.com
#
# usage:
#   rx_* l archive directory   # list archive directory
#   rx_* v archive             # list entire archive
#   rx_* x archive files...    # extract one file
#   rx_* x archive @listfile   # extract list of files
#
#############################################################################
use strict;

my $CTTL = 16; # cache time to live in seconds

my $file = $ARGV[1];

for( glob "/tmp/*.rx.cache" )
  {
  # clean cache--silently skip errors
  next unless time() - file_mtime( $_ ) > $CTTL;
  unlink $_;
  }

my $rx = choose( $file ) or die "$0: this file type is not known to me, sorry\n";

exec_if_exists( "/usr/libexec/vfu/$rx", @ARGV );
exec_if_exists( "$ENV{HOME}/bin/$rx", @ARGV );
die "$0: cannot find and/or execute [$rx]\n";

sub choose
{
  local $_ = shift;
  return "rx_tar" if /\.(tar(\.(z|gz|xz|bz2|zst))?|t[bgx]z)$/i;
  return "rx_zip" if /\.(zip|jar|pk3|egg|maff)$/i;
  return "rx_deb" if /\.deb$/i;
  return "rx_ftp" if /\.ftp$/i;
  return "rx_rar" if /\.rar$/i;
  return "rx_rpm" if /\.rpm$/i;
  return undef;
}

sub file_mtime
{
  return (stat($_[0]))[9];
}

sub exec_if_exists
{
  my $rxbin = shift;
  return undef unless -x $rxbin;
  exec( $rxbin, @_ );
}
