#!/usr/bin/perl

# If you use this script, be sure to add
#   /var/lib/SatTrack/tle/amsat.dat
# to the START of
#  /etc/sattrack/tlelist.dat
# (or at least before the ones in /usr. If you have newer ones again,
# list them before that file.)

# Written by Hamish Moffatt VK3SB; released as GPL. 
# See /usr/doc/copyright/GPL.

# Revised 04/04/1999 to use libwww instead of lynx to obtain the data
# Bug fixes 03/01/2000 to handle carriage returns in downloaded data
# Bug fixes 25/04/2000 to check maketlex's result code

###########################################################################

use LWP::UserAgent;

$URL = "http://www.amsat.org/amsat/ftp/keps/current/nasa.all";
$OUTPUT = "/var/lib/SatTrack/tle/amsat.dat";

open(output, ">$OUTPUT") 
  or die("Could not open $OUTPUT for writing; not root?\n");

$ua = new LWP::UserAgent;
$ua->env_proxy();
my $req = new HTTP::Request GET => $URL;
my $res = $ua->request($req);

if (not $res->is_success) {
  die "Could not obtain new elements from $URL\n";
}

$foundit = 0;

@out = split(/\n/, $res->content);

foreach $in (@out) {
    chomp $in;
    $in =~ s/\cm$//; # strip carriage returns
    next if ($in eq "");

    $foundit = 0 if ($in =~ /^EX/);
    print output "$in\n" if ($foundit);
    $foundit = 1 if ($in =~ m/^TO ALL RADIO AMATEURS BT/);

}

close(output);

(system "/usr/sbin/maketlex" == 0) or die "Errors occurred during maketlex\n";
