#!/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
#
#############################################################################
#
# BUGS: 
# - cannot show recursively entire site
# - cannot copy/extract directories
#
# TODO:
# - cache?
#
#############################################################################
use strict;
use Net::FTP;

umask 0077;

my $cmd = lc shift @ARGV;
my $archive = shift @ARGV;
my $cache = "/tmp/$archive.rx.cache";
$cache =~ s/^(\/tmp\/)(.+)\/([^\/]+)$/$1$3/;

my $i;
open $i, $archive;
my $host = <$i>;
my $user = <$i>;
my $pass = <$i>;
close $i;
chop($host);
chop($user);
chop($pass);

my $ftp = Net::FTP->new( $host ) or die "$0: cannot connect to $host\n";

$user = 'anonymous' if $user eq '-';
$pass = "$ENV{USER}\@$ENV{HOSTNAME}" if $pass eq '-';
$ftp->login( $user, $pass ) or die "$0: cannot login as $user into $host\n";

if ( $cmd eq "l" || $cmd eq "v" )
  {
  my $dir = shift @ARGV;
  $ftp->cwd( $dir );
  
  my @list = $ftp->dir();
  for( @list )
    {
    my @D = split /\s+/, $_;
    my $N = pop @D;
    my $M = $D[0];
    my $S = $D[4];
    $N .= '/' if $M =~ /^d/i;
    print "NAME:$N\nSIZE:$S\nMODE:$M\n\n";
    }
  }
elsif ( $cmd eq "x" )
  {
  my @list;
  if ( $ARGV[0] =~ /^\@(.+)$/ )
    {
    my $i;
    open $i, $1;
    @list = <$i>;
    close $i;
    chop( @list );
    }
  else
    {
    @list = @ARGV;
    }
  for my $e ( @list )  
    {
    $e =~ s/^\///;
    my $p;
    my $l;
    if( $e =~ /^(.+\/)([^\/]+)$/ )
      {
      $l = $2;
      $p = $1;
      };
    mkpath( $p );
    # print "$e:$p:$l\n";
    $ftp->get( $e, "$p$l" );
    }
  }
else
  {
  die $0 . ": wrong command.\n";
  }


sub mkpath
{
  my $p = shift;
  my @p = split /\//, $p;
  my $cp;
  while( @p )
    {
    $cp .= shift( @p ) . '/';
    mkdir $cp;
    print ">>$cp\n";
    }
}

