#-------------------------------------------------------------------------------
# This file is part of the FLARM¨-Radar Project.
#   
#   Copyright 2013 Netzschmiede GmbH (http://www.netzschmiede.ch)
# 
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# 
#   http://www.apache.org/licenses/LICENSE-2.0
# 
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# 
#   Project Website: www.flarmradar.ch
#   Email: info@flarmradar.ch
#-------------------------------------------------------------------------------
#!/usr/bin/perl

use strict;
use Getopt::Std;
# load LWP library:
use LWP::UserAgent;
use HTML::Parse;
use Time::HiRes;

# parse options
my %options;
getopts('f:u:s:', \%options);
unless(defined($options{'f'}) && defined($options{u})) {
  usage();
}

my $url = $options{u};
my $file = $options{f};
my $speed = defined($options{s}) ? $options{s} : 1; 
if (! -f $file || ! -w $file) {
  print "error reading input file: ", $file, "\n";
  exit 1;
}


 

# create UserAgent object
my $ua = new LWP::UserAgent;
 
# set a user agent (browser-id)
# $ua->agent('Mozilla/5.5 (compatible; MSIE 5.5; Windows NT 5.1)');
 
# timeout:
$ua->timeout(15);

my $i = 0;
my $buf;

open(FILE, "< $file") || die("error while reading file ", $file);
while (my $record = <FILE>) {
  chomp($record);
  if ($record =~ /^\$GPGGA,/) {
    flush($buf, $url, $i);
    #sleep(1);
    Time::HiRes::sleep(1/$speed);
    $buf = undef;
  }
  $i++;
  $buf = (defined($buf)) ? "$buf;$record" : $record;  
}
flush($buf, $url, $i);
close(FILE);

exit 0;

sub flush() {
  my ($records, $url, $count) = @_;
  my $request = HTTP::Request->new('PUT');
  $request->url($url);
  $request->content($records);
  print "flushing at $count\n";
  # run the request
  my $response = $ua->request($request);
  my $code = $response->code;
  die("error processing records ", $records) if (200 != $response->code); 
}
# proceed the request:
my $request = HTTP::Request->new('PUT');
$request->url($url);
$request->content("blubb");
 
my $response = $ua->request($request);
 
 
#
# responses:
#
 
# response code (like 200, 404, etc)
my $code = $response->code;
print "Return code: ", $code, "\n";
 
# headers (Server: Apache, Content-Type: text/html, ...)
my $headers = $response->headers_as_string;
print "Headers: ", $headers, "\n";
 
# HTML body:
my $body =  $response->content;
print "Body: ", $body, "\n";

sub usage() {
  print "usage: bulb\n";
  exit 1;
}
