#!/usr/bin/perl -w

# CLI client for the FEX service for retrieving files
#
# see also: fexsend
#
# Author: Ulli Horlacher <framstag@rus.uni-stuttgart.de>
#
# Copyright: GNU General Public License

use 5.006;
use strict qw(vars subs);
use POSIX;
use Encode;
use Getopt::Std;
use Socket;
use IO::Handle;
use IO::Socket::INET;
use I18N::Langinfo qw(langinfo CODESET);
use constant k => 2**10;
use constant M => 2**20;
  
our $SH;
our $bs = 2**16; # blocksize for tcp-reading and writing file
our $version = 20110726;

$version = mtime($0) unless $version;

$0 =~ s:.*/::;
$| = 1;


my $usage = <<EOD;
usage: $0 [-v] [-m limit] [-s filename] [-o] [-k] [-X] F*EX-URL ...
   or: $0 [-v] -d F*EX-URL ...
   or: $0 [-v] -a
   or: $0 -l [-i tag]
options: -v verbose mode
         -m limit kB/s
         -s save to filename (-s- means: write to STDOUT/pipe)
         -o overwrite existing file
  	 -k keep on server after download
  	 -X do not extract archive files
  	 -d delete without download
         -a get all files (implies -X)
  	 -l list files on server 
         -i tag alternate server/account, see: fexsend -h
argument: F*EX-URL may be file number (see: $0 -l)
EOD
  
my $tmpdir = $ENV{FEXTMP} || $ENV{HOME}.'/.fex/tmp';
my $atype = '\.(tgz|tar|zip|7z)$';

our ($opt_h,$opt_v,$opt_l,$opt_d,$opt_m,$opt_z,$opt_K,$opt_o,$opt_a);
our ($opt_s,$opt_k,$opt_i,$opt_V,$opt_X);
$opt_m = $opt_h = $opt_v = $opt_l = $opt_d = $opt_K = $opt_o = $opt_a = 0;
$opt_V = $opt_X = 0;
$opt_s = $opt_k = $opt_i = '';
getopts('hvVldkzoaXm:s:i:K:') or die $usage;
$opt_k = '?KEEP' if $opt_k;

if ($opt_m =~ /(\d+)/) { 
  $opt_m = $1 
} else { 
  $opt_m = 0
}

if ($opt_V) {
  print "Version: $version\n";
}

my $ffl = "$tmpdir/fexget"; 		# F*EX files list (cache)
my $useragent;

$_ = `(lsb_release -d||uname -a)2>/dev/null`||'';
chomp;
s/^Description:\s+//;
$useragent = "fexget-$version ($_)";

# get fexlog
if ($opt_z) {
  my $cmd = "fexsend -Z";
  $cmd .= " -i $opt_i" if $opt_i;
  warn "$cmd\n" if $opt_v;
  exec $cmd;
  die "$0: cannot run $cmd : $!\n";
}

if ($opt_l) {
  my $cmd = "fexsend -L";
  $cmd .= " -i $opt_i" if $opt_i;
  if ($opt_v) {
    $cmd .= " -v";
    warn "$cmd\n";
  }
  open $cmd,"$cmd|" or die "$0: cannot run $cmd : $!\n";
  open $ffl,'>',$ffl or die "$0: cannot open $ffl : $!\n";
  my $n;
  while (<$cmd>) {
    if (/\d MB http/) {
      $n++;
      printf {$ffl} "%4d) %s",$n,$_;
      s:http[^\"]*/::;
      printf        "%4d) %s",$n,$_;
    } else {
      print;
      print {$ffl} $_;
    }
  }
  exit;
}

die $usage if $opt_h;

if ($opt_a) {
  $opt_X = $opt_a;
  die $usage if @ARGV;
  system qw(fexget -l);
  print "\n";
  if (open $ffl,$ffl) {
    while (<$ffl>) {
      push @ARGV,$1 if /^\s+(\d+)/;
    }
    close $ffl;
  }
} else {
  die $usage unless @ARGV;
}

my ($file,%files,$download,$server,$port,$fop);
  
foreach my $url (@ARGV) {
  
  # do not overrun server
  sleep 1 if $fop;

  if ($url !~ /^http/) {
    unless (%files) {
      open $ffl,$ffl or die "$0: no $ffl, use first: $0 -l\n";
      my $from = '';
      while (<$ffl>) {
        if (/^from (.+) :$/) {
          $from = $1;
        } elsif (/^\s*(\d+)\)\s+\d+ MB (\S+)/) {
          push @{$files{all}},$2;
          push @{$files{$from}},$2;
        }
      }
      close $ffl;
    }

    if ($url =~ /^(\d+)$/) {
      $url = ${files{all}}[$1-1] or die "$0: unknown file number\n";
    }
  }

  if ($url =~ m{^http(s?)://([\w\.\-]+)(:(\d+))?(/fop/\S+)}) {
    $server = $2;
    $port   = $4 || ($1?443:80);
    $fop    = $5;
  } else {
    die "$0: unknown F*EX URL $url\n";
  }
  
  tcpconnect($server,$port);

  if ($opt_d) {
    my @r = del($url);
    $_ = shift @r;
    if (/^HTTP.* 200/) {
      ($file) = grep { $_ = $1 if /^X-File:\s+(.+)/ } @r;
      $file = $url unless $file;
      $file =~ s:.*/::;
      print "$file deleted\n";
    } else {
      s:HTTP/[\d\. ]+::;
      die "$0: server response: $_";
    }
    next;
  }

  if ($opt_K) {
    my @r = keep($url);
    $_ = shift @r;
    if (/^HTTP.* 200/) {
      $file = $url;
      $file =~ s:.*/::;
      print "$file kept\n";
    } else {
      s:HTTP/[\d\. ]+::;
      die "$0: server response: $_";
    }
    next;
  }

  $download = download($server,$port,$fop);
  exit if $opt_s eq '-';
  unlink $download unless -s $download;
  exit 2 unless -f $download;

  if (not $opt_X and $download =~ /$atype/) {
    if (-t) {
      print "Files in archive:\n";
      if ($download =~ /\.tgz$/) {
        system qw(tar tvzf),$download;
        &cont; 
        system qw(tar xvzf),$download;
      } elsif ($download =~ /\.tar$/) {
        system qw(tar tvf),$download;
        &cont; 
        system qw(tar xvf),$download;
      } elsif ($download =~ /\.zip$/i) {
        system qw(unzip -l),$download;
        &cont; 
        system qw(unzip),$download;
      } elsif ($download =~ /\.7z$/i) {
        system qw(7z l),$download;
        &cont; 
        system qw(7z x),$download;
      } else {
        die "$0: unknown archive $download\n"; 
      }
    } else {
      if    ($download =~ /\.tgz$/)  { system qw(tar xvzf),$download }
      elsif ($download =~ /\.tar$/)  { system qw(tar xvf),$download }
      elsif ($download =~ /\.zip$/i) { system qw(unzip),$download }
      elsif ($download =~ /\.7z$/i)  { system qw(7z x),$download }
      else                           { die "$0: unknown archive $download\n" }
    }
    if ($? == 0) {
      unlink $download;
    } else {
      die "$0: keeping $download\n";
    }
  }  

}

exit;

sub cont {
  print "extract these files (Y/n)? ";
  $_ = <STDIN>||'y';
  unless (/^y/i) {
    print "keeping $download\n";
    exit;
  }
}

sub del {
  my $url = shift;
  my ($server,$port);
  my $del;
  my @r;
  
  if ($url =~ m{^http(s?)://([\w\.\-]+)(:(\d+))?(/fop/.+)}) {
    $server = $2;
    $port   = $4 || ($1?443:80);
    $del    = $5.'?DELETE';
  } else {
    die "$0: unknown F*EX URL $url\n";
  }
  
  sendheader("$server:$port","GET $del HTTP/1.1","User-Agent: $useragent");
  while (<$SH>) { 
    s/\r//;
    last if /^\n/; # ignore HTML output
    print "<-- $_" if $opt_v;
    push @r,$_;
  }
  die "$0: no response from fex server $server\n" unless @r;
  return @r;
}


sub keep {
  my $url = shift;
  my ($server,$port);
  my $keep;
  my (@hh,@r);
  
  if ($url =~ m{^http(s?)://([\w\.\-]+)(:(\d+))?(/fop/.+)}) {
    $server = $2;
    $port   = $4 || ($1?443:80);
    $keep    = "$5?KEEP=$opt_K";
  } else {
    die "$0: unknown F*EX URL $url\n";
  }
  
  push @hh,"GET $keep HTTP/1.1",
           "Host: $server:$port",
           "User-Agent: $useragent",
           "";
  
  foreach (@hh) {
    warn $_,"\n" if $opt_v;
    print $SH $_,"\r\n";
  }
  while (<$SH>) { 
    s/\r//;
    last if /^\n/;
    push @r,$_;
  }
  die "$0: no response from fex server $server\n" unless @r;
  grep { warn "\t$_" } @r if $opt_v;
  return @r;
}


sub download {
  my ($server,$port,$fop) = @_;
  my ($file,$download,$ssl,$pipe,$filesize);
  my (@hh,@r);
  my ($t0,$t1,$t2,$tm,$ts,$kBs,$b,$bt,$tb,$B,$buf);
  my $length = 0;
  my $seek = 0;
  local $_;
  local *X;

  if ($opt_s) {
    $file = $opt_s;
    if ($opt_s eq '-') {
      $pipe = $download = $opt_s;
    } elsif (-p $opt_s or -c $opt_s) {
      $download = $opt_s;
    } else {
      $download = $file.'.tmp';
      $seek = -s $download || 0;
    }
  } else {
    # ask server for real file name
    sendheader("$server:$port","HEAD $fop HTTP/1.1","User-Agent: $useragent");
    my $reply = $_ = <$SH>;
    unless (defined $_ and /\w/) { 
      die "$0: no response from server\n";
    }
    unless (/^HTTP\/[\d.]+ 200/) {
      s:HTTP/[\d. ]+::;
      die "$0: server response: $_";
    }
    while (<$SH>) { 
      s/\r//;
      print "<-- $_" if $opt_v;
      last if /^\r?\n/;
      if (/^Content-Disposition: attachment; filename="(.+)"/i) {
        $file = locale(decode_utf8($1));
          $file =~ s:.*/::;
      }
    }
    die $reply unless $file;
    $download = $file.'.tmp';
    $seek = -s $download || 0;
  }
  
  push @hh,"GET $fop$opt_k HTTP/1.1",
           "User-Agent: $useragent";
  push @hh,"Range: bytes=$seek-" if $seek;
  
  sendheader("$server:$port",@hh);
  $_ = <$SH>;
  die "$0: no response from fex server $server\n" unless $_;
  s/\r//;
  
  if (/^HTTP\/[\d.]+ 2/) {
    warn "<-- $_" if $opt_v;
    while (<$SH>) {
      s/\r//;
      print "<-- $_" if $opt_v;
      last if /^\r?\n/;
      if (/^Content-length:\s*(\d+)/i) { 
        $length = $1;
      } elsif (/^X-Size: (\d+)/i) {
        $filesize = $1;
      }
    }
  } else {
    s/HTTP\/[\d.]+ \d+ //;
    die "$0: bad server reply: $_";
  }
  
  if ($pipe) {
    *X = *STDOUT;
  } else {
    if ($opt_s and $opt_s eq $download) {
      open X,'>',$download or die "$0: cannot write to $download - $!\n";
    } else {
      if (-e $file and not $opt_o) { 
        die "$0: destination file \"$file\" does already exist\n";
      }
      if ($seek) {
        open X,'>>',$download or die "$0: cannot write to $download - $!\n";
      } else {
        open X,'>',$download or die "$0: cannot write to $download - $!\n";
      }
    }
  }
  
  $t0 = $t1 = $t2 = time;
  $tb = $B = 0;
  printf STDERR "resuming at byte %d\n",$seek if $seek;
  while ($b = read $SH,$buf,$bs and $B < $length) {
    syswrite X,$buf;
    $B += $b;
    $tb += $b;
    $bt += $b;
    $t2 = time;
    if ($t2 > $t1) {
      $kBs = int($bt/k/($t2-$t1));
      $kBs = int($tb/k/($t2-$t0)) if $kBs < 10;
      $t1 = $t2;
      $bt = 0;
      # smaller block size is better on slow links
      $bs = 4096 if $bs>4096 and $tb/($t2-$t0)<65536;
      if ($tb<2*M) {
        printf STDERR "%s: %d kB (%d%%) %d kB/s \r",
                      $download,
                      int(($tb+$seek)/k),
                      int(($tb+$seek)/($length+$seek)*100),
                      $kBs;
      } else {
        printf STDERR "%s: %d MB (%d%%) %d kB/s        \r",
                      $download,
                      int(($tb+$seek)/M),
                      int(($tb+$seek)/($length+$seek)*100),
                      $kBs;
      }
    }
    if ($opt_m) {
      if ($t2 == $t0 and $B > $opt_m*k) { 
        print "\nsleeping...\r" if $opt_v;
        sleep 1;
      } else {
        while ($t2 > $t0 and $tb/k/($t2-$t0) > $opt_m) {
          print "\nsleeping...\r" if $opt_v;
          sleep 1;
          $t2 = time;
        }
      }
    }
  }
  close $SH;
  close X;
  
  $tm = int(($t2-$t0)/60);
  $ts = $t2-$t0-$tm*60;
  $kBs = int($tb/k/(($t2-$t0)||1));
  if ($seek) {
    printf STDERR "$file: %d MB, last %d MB in %d:%02d = %d kB/s   \n",
                  int(($tb+$seek)/M),int($tb/M),$tm,$ts,$kBs;
  } else {
    printf STDERR "$file: %d MB in %d:%02d = %d kB/s   \n",
                  int($tb/M),$tm,$ts,$kBs;
  }
  
  if ($tb != $length) {
    die "$0: $server annouced $length bytes, but only $tb bytes has been read\n";
  }
  
  unless ($pipe or -p $download or -c $download) {
    my @s = stat $file if -e $file;
    rename $download,$file 
      or die "$0: cannot rename \"$download\" to \"$file\" - $!\n";
    chmod $s[2],$file if @s;
  }
  
  return $file;
}


# set up tcp/ip connection
sub tcpconnect {
  my ($server,$port) = @_;
  
  if ($port == 443) {
    eval "use IO::Socket::SSL";
    $SH = IO::Socket::SSL->new(
      PeerAddr => $server,
      PeerPort => $port,
      Proto    => 'tcp',
    );
  } else {
    $SH = IO::Socket::INET->new(
      PeerAddr => $server,
      PeerPort => $port,
      Proto    => 'tcp',
    );
  }
  die "cannot connect $server:$port - $@\n" unless $SH;
  print "TCPCONNECT to $server:$port\n" if $opt_v;
}


sub locale {
  my $string = shift;
  my $CTYPE = langinfo(CODESET);

  if ($CTYPE) {
    if ($CTYPE =~ /UTF-?8/i) {
      return $string;
    } elsif (grep { $CTYPE =~ /^$_$/i } Encode->encodings()) {
      return encode($CTYPE,$string);
    } else {
      return encode('ISO-8859-1',$string);
    }
  }

  return $string;
}


sub sendheader {
  my $sp = shift;
  my @head = @_;
  my $head;
  
  push @head,"Host: $sp";
  
  foreach $head (@head) {
    print "--> $head\n" if $opt_v;
    print {$SH} $head,"\r\n";
  }
  print "-->\n" if $opt_v;
  print {$SH} "\r\n";
}


sub mtime {
  my @d = localtime((stat shift)[9]);
  return sprintf('%d%02d%02d',$d[5]+1900,$d[4]+1,$d[3]);
}
