#! /usr/local/bin/perl

use Net::FTP;
use strict;

print "Enter FTP Server : ";
my $server = <STDIN>;
chomp $server;
my @lsdir;
my $current;
our $ftp = undef;
our $cmd;
my $subcmd;
$ftp = Net::FTP->new($server)		or die "Couldn't connect to " ,$server ," !\n";
if ($ftp) {
	system("clear");
    print "You are connected to ", $server ,"\n";
	anon:
	print "Would you like to login as 'Anonymous'? y/n: ";
	my $anon = <STDIN>;
	chomp $anon;
	if ($anon =~ /^y$/i) {
		$ftp->login()	or die "Anonymous login failed! Quitting... \n";
		print "Anonymous login successful!\n";
	} elsif ($anon =~ /^n$/i) {
		print "Please enter username: ";
		my $username = <STDIN>;
		chomp $username;
		print "Please enter password: ";
		my $password = <STDIN>;
		chomp $password;
		$ftp->login($username, $password)	or die "Login failed! Quitting... \n";
	} else {
		print "Unknown command!\n\n";
		goto anon;
	}
	$current = $ftp->pwd();
	print "\n\nYou are here: ", $current ,"			on ", $server ,"\n\n";
	@lsdir = $ftp->dir();
	print join ("\n",@lsdir);
	do {
	print "\n\nYou are now in command mode. Enter 'help' to list supported commands.\n\n";
	print "Command: ";
	$cmd = <STDIN>;
	chomp $cmd;
	command(split(/\s+/,$cmd));
	} while ($cmd !~ /^quit$/i);
	$ftp->quit();
	die "\n\n\nConnection terminated! Goodbye!\n\n";
}

sub command {
	my @args=@_;
	if ($args[0] =~ /^help$/i) {
		print "Help is not available yet!";
	} elsif ($args[0] =~ /^cwd$/i || $args[0] =~ /^cd$/i) {
		print "CWD command executed with argument: ", $args[1] ,"\n\n";
		$ftp->cwd($args[1]);
		$current = $ftp->pwd();
		print "\n\nYou are here: ", $current ,"			on ", $server ,"\n\n";
	} elsif ($args[0] =~ /^dir$/i ) {
		@lsdir = $ftp->dir();
		print join ("\n",@lsdir), "\n";
	} elsif ($args[0] =~ /^pwd$/i ) {
		$current = $ftp->pwd();
		print "\nYou are here: ", $current ,"			on ", $server ,"\n";
	} elsif ($args[0] =~ /^ls$/i ) {
		@lsdir = $ftp->ls();
		print join ("\n",@lsdir), "\n";
	} elsif ($args[0] =~ /^get$/i ) {
		print "\nCopying file ", $server ,$current ,"/" ,$args[1] ,"   to   " ,$args[2] ,"\n\n";
		print "Copying... Please be patient while waiting! ;-)\n\n";
		$ftp->get($args[1], $args[2]);
		#system("clear");
		print "Copying finished!\n";
	} elsif ($args[0] =~ /^put$/i ) {
		print "\nDownloading file " ,$args[1], "   to   ", $server ,$current ,"/" ,$args[2] ,"\n\n";
		print "Downloading... Please be patient while waiting! ;-)\n\n";
		$ftp->put($args[1], $args[2]);
		print "Downloading finished!\n";
	}
}

#sub help {
#	print 