#!/usr/bin/perl

use Net::FTP;

my $method = 'ftp';
my $user = $ENV{FTP_USER} || undef;
my $password = $ENV{FTP_PASSWORD} || undef;
my $host = "10.9.25.1"; # glazed.cobalt.com
my $dir = "/fargo/carmel/rpms";
my @files = ();

while(defined($_ = shift(@ARGV))) {
  if (m/^-u(\S*)/) { $user = $1 || shift(@ARGV); }
  elsif (m/^-p(\S*)/) { $password = $1 || shift(@ARGV); }
  elsif (m/^-h(\S*)/) { $host = $1 || shift(@ARGV); }
  elsif (m/^-d(\S*)/) { $dir = $1 || shift(@ARGV); }
  # elsif (m/^-x(\S*)/) { parse_url($1 || shift(@ARGV)); }
  else { push (@files, $_); }
}

if ($#files < 0) { print STDERR <<EOT ; exit 1; }
Usage: $0 
  [-u username] [-p password] [-h hostname] [-d directory]
  files...

Environment variables:
  FTP_USER -- username to use for ftp connections.
  FTP_PASSWORD -- password to use for ftp connections.

EOT

if (!$user) {
  print STDERR "username: ";
  $user = <STDIN>;
  chomp($user);
}
if (!$password) {
  print STDERR "password: ";
  $password = <STDIN>;
  chomp($password);
}

$ftp = Net::FTP->new($host) || die ("Couldn't connect to $host: $!\n");
$ftp->login($user, $password) || 
  die ("Couldn't authenticate to $host as $user: $!\n");
$ftp->cwd($dir) ||
  die ("Couldn't cwd to $dir: $!\n");
$ftp->binary();

foreach $_ (@files) 
{
  print STDERR "putting $_ -> $host:$dir/$_: ";
  if ($ftp->put($_)) {
    print STDERR "ok\n";
  } else {
    print STDERR "failed: $!\n";
  }
}

$ftp->quit();
