#!/bin/perl

#use 5.1;

use Net::Ping;
use LWP::Simple;
use JSON;
use Data::Dumper;

use experimental qw ( switch );
use vars qw ( $VERSION @ISA @EXPORT );
use strict;

$| = 1;

my $APEMANIP = "192.168.0.1";
my $dir = "Downloads";

if ( ! -d "$dir" ) {
   print "Downloads Verzeichnis '$dir' existiert nicht. Versuche es anzulegen.\n";
   my $ok=mkdir("$dir", 0777);
   if ( ! $ok ) {
      print "Verzeichnis konnte nicht angelegt werden\n";
      exit 1;
   }
}


print "\nWarten auf Apeman\n";
my $p = Net::Ping->new();
while ( ! $p->ping($APEMANIP) )    {
   ;
}
$p->close();

my $url = "http://$APEMANIP/cgi-bin/hi3510/getfilelistinfoios.cgi";
if ( get($url) eq "SvrFuncResult=\"-5555\"" ){
   print "Apeman gefunden\n\n";

   $url = "http://$APEMANIP/cgi-bin/hi3510/getfilelistinfoios.cgi?-start=1&-end=30";
   my $raw = get($url);
   my @content  = decode_json($raw);
   my $nofile = 1;
   foreach my $c ( @content ) {
      foreach my $k ( @{$c} ) {
         $url = "http://$APEMANIP/" . $k->{'path'};
         my ($file) = $k->{'path'} =~ /([^\/]*\.[a-z0-9]*)$/i;
         
         my $create = $k->{'create'};
         $create =~ tr/\//-/;
         $create =~ tr/:/-/;
         $create =~ tr/ /_/;
         
         $file = $dir . "/" . $create . "_" . $file;
         print "Download $url to $file\n";
         
         getstore($url, $file);
         print "Lösche $file von Apeman\n";
         $url = "http://$APEMANIP/cgi-bin/hi3510/deletefile.cgi?-name=" . $k->{'path'};
         $raw = get($url);
         chomp $raw;
         
         if ($raw =~ /Success/) {
            print "OK\n\n";
         } else {
            print "Nicht OK\n\n";
         }
         $nofile = 0;
      }
   }
   if ( $nofile ) {
      print "Keine Datei verfügbar\n";
   } else {
      print "Download abgeschlossen\n";
   }
}
