#!/usr/bin/perl  
# ftp_url.pl
# Ftp URL listing
# RJM Programming
# November, 2017
# Thanks to https://www.foo.be/docs/tpj/issues/vol1_3/tpj0103-0007.html

use Net::FTP; 	
#use File::Listing qw(parse_dir); 	

# Create a new connection to the ftp server  
sub connection {    # Create a new NET::FTP object  
        $ftp = Net::FTP->new($CPANhost, Timeout => 60) 
               or die "Can't contact $CPANhost: $!";  
        # We shall login to the ftp server as anonymous; 	          
        $ftp->login($CPANusername,$CPANpassword) 
               or die "Can't login ($CPANhost):" . 
               $ftp->message;  
        # Change the working directory  
        $ftp->cwd($CPANpath) or die 
               "Can't change directory ($CPANhost):". 
               $ftp->message;  
        return $ftp; 
    }  
    
    
# The path to the CPAN/modules directory on most CPAN hosts
$CPANpath = '/';  

$CPANusername = 'mkuulma@ozemail.com.au';
$CPANpassword = '';
    
# Change this to the name of your nearest CPAN host
$CPANhost = '';
my $size = @ARGV;
if ($size == 2) { 
  $CPANhost = 'ftp.ozemail.com.au';  
  $CPANpath = $ARGV[1];  
  $CPANpassword = $ARGV[0];
} else {
 if ($size == 1) { 
  $CPANhost = 'ftp.ozemail.com.au';  
  $CPANpassword = $ARGV[0];
 } else {
  if ($size == 3) { 
   $CPANhost = $ARGV[0];  
   $CPANusername = $ARGV[1];
   $CPANpassword = $ARGV[2];
  } else {
   if ($size == 4) { 
    $CPANhost = $ARGV[0];  
    $CPANusername = $ARGV[1];
    $CPANpassword = $ARGV[2];
    $CPANpath = $ARGV[3];  
   } else {
    print "Usage is via ... perl ftp_url.pl [ftphost=ftp.ozemail.com.au] [ftpusername=mkuulma@ozemail.com.au] ftppassword [subpath=/]\n";
   }
  }
 }
}

if ($CPANpassword eq '') {
 $CPANpassword = '';
} else {
 # Create the initial connection 	
 $ftp = connection();  

 $ftp->pasv(); # passive mode

 # Retrieve a recursive directory listing 
 my @ls = $ftp->ls('-l');  

 for my $filex (@ls) {
  my $file = $filex;
  my (@description, $size);
  if (-e $file) {
   push @description, 'binary' if (-B _);
   push @description, 'a socket' if (-S _);
   push @description, 'a text file' if (-T _);
   push @description, 'a block special file' if (-b _);
   push @description, 'a character special file' if (-c _);
   push @description, 'a directory' if (-d _);
   push @description, 'executable' if (-x _);
   push @description, (($size = -s _)) ? "$size bytes" : 'empty';
   push @description, (($daysago = -M _)) ? " modified $daysago days ago" : '';
   print "\n\t$file is ", join(', ',@description),"";
  }
 }
 print "\n\t";
}

