#!/usr/bin/env perl

use 5.006002;

use strict;
use warnings;

use Astro::SpaceTrack;
use Astro::Coord::ECI::Utils qw{ max };
use Data::Dumper;
use Getopt::Long 2.33 qw{ :config auto_version };
use HTTP::Date;
use LWP::UserAgent;
use Pod::Usage;

our $VERSION = '0.110';

my %opt;

GetOptions( \%opt,
    qw{ debug! decayed! merge! },
    help => sub { pod2usage( { -verbose => 2 } ) },
) or pod2usage( { -verbose => 0 } );


my $ast = Astro::SpaceTrack->new();
my $ua = LWP::UserAgent->new();
my $mask = 1;
my $all = 0;
my @sources;
my @source_timestamp;
my %found;
my $date = 0;
my %vsnames;

foreach my $code (
    sub {
	return (
	    'Celestrak visual',
	    $ua->get( 'http://celestrak.com/SpaceTrack/query/visual.txt'),
	);
    },
    sub {
	return (
	    'McCants vsnames',
	    $ast->mccants( 'vsnames' ),
	);
    }
) {
    my ( $source, $rslt ) = $code->();
    process( $source, $rslt, sub {
	    my ( $oid, $line ) = @_;
	    $found{$oid} |= $mask;
	    if ( defined( my $mag = unpack_mag( $line ) ) ) {
		$opt{debug}
		    and warn "        $oid $mag\n";
		$vsnames{$oid} = $mag;
	    }
	} );
    $sources[$mask] = $source;
    $all |= $mask;
    $mask <<= 1;
}

my %quicksat;

if ( $opt{merge} ) {
    my $rslt = $ast->mccants( 'quicksat' );
    process( 'McCants quicksat', $rslt, sub {
	    my ( $oid, $line ) = @_;
	    37 > length $line
		and $line = sprintf '%-37s', $line;
	    my $mag = unpack 'x33a4', $line;
	    $mag =~ s/ \s+ //smxg;
	    $mag =~ m/ \A -? [0-9.]+ \z /smx
		or return;
	    $mag += 1.4;	# Different intrinsic magnitude definition.
	    $opt{debug}
		and warn "        $oid $mag\n";
	    $quicksat{$oid} = $mag;
	    return;
	} );
    foreach my $oid ( keys %found ) {
	defined( $found{$oid} = dor( $vsnames{$oid}, $quicksat{$oid} ) )
	    or delete $found{$oid};
    }
    # Unless we have a number for Tiangong 2, make it the same as
    # Tiangong 1.
    my $tiangong2;
    unless ( defined $found{41765} ) {
	if ( defined $found{37820} ) {
	    $found{41765} = $found{37820};
	    $tiangong2 = ' # Assumed same as Tiangong 1';
	} else {
	    $found{41765} = 3.9;
	    $tiangong2 = ' # Assumed 3.9 (old Tiangong 1 value)';
	}
    }
    $opt{decayed}
	and decayed( \%found );
    local $Data::Dumper::Terse = 1;
    local $Data::Dumper::Sortkeys = 1;
    my $output = Dumper ( \%found );
    $output =~ s/ \A \s* [{] /%magnitude_table = (/smx;
    $output =~ s/ [}] \s* \z /);\n/smx;
    $output =~ s/ ' ( -? \d+ [.] \d+ ) ' /$1/smxg;
    $output =~ s/ (?<= \d ) (?: (?= \n ) | \z ) /,/smxg;
    defined $tiangong2
	and $output =~ s/ \b ( 41765 \b [^\n]* ) /$1$tiangong2/smx;
    my @asserted = map { "-$_" } grep { $opt{$_} } qw{ decayed merge };
    print <<"EOD";
# The following is all the Celestrak visual list that have magnitudes in
# either McCants' vsnames.mag or quicksat.mag files, with the former
# being preferred. The QuickSat magnitudes assume a different
# illumination and phase angle, and are adjsted by adding 1.4. These
# data are generated by the following:
#
#   \$ eg/visual @asserted
#
# Last-Modified: @{[ time2str( $date ) ]}

# The following constants are unsupported, and may be modified or
# revoked at any time. They exist to support
# xt/author/magnitude_status.t
EOD

    my $wid = max( map { length $_->[0] } @source_timestamp );
    foreach my $src ( @source_timestamp ) {
	( my $const = uc $src->[0] ) =~ s/ \W /_/smxg;
	printf "use constant _%-${wid}s => '$src->[1]';\n", $const;
    }

    print "\n", $output;
} else {
    $opt{decayed}
	and decayed( \%found );
    foreach my $oid ( sort { $a <=> $b } keys %found ) {
	$found{$oid} == $all
	    and next;
	print "$oid $sources[$found{$oid}]\n";
    }
    print 'Last-Modified: ', time2str( $date ), "\n";
}

sub decayed {
    my ( $found ) = @_;
    require Astro::SpaceTrack;
    require JSON;
    my $st = Astro::SpaceTrack->new(
	identity	=> 1,
	pretty		=> 1,
    );
    my $rslt = $st->search_oid( {
	    format	=> 'json',
	    status	=> 'all',
	    tle		=> 0,
	}, keys %{ $found } );
    my $json = JSON->new()->utf8();
    foreach my $obj ( @{ $json->decode( $rslt->content() ) } ) {
	defined $obj->{DECAY}
	    or next;
	$opt{debug}
	    and warn "        $obj->{NORAD_CAT_ID} decayed $obj->{DECAY}\n";
	delete $found->{$obj->{NORAD_CAT_ID}};
    }
    return $found;
}

sub dor {
    my @arg = @_;
    foreach my $val ( @arg ) {
	defined $val
	    and return $val;
    }
    return $arg[0];
}

sub last_modified {
    my ( $source, $resp ) = @_;
    my ( $last_modified ) = $resp->header( 'Last-Modified' );
    push @source_timestamp, [ $source, $last_modified ];
    defined $last_modified
	or return;
    return str2time( $last_modified );
}

sub process {
    my ( $source, $rslt, $process ) = @_;
    $opt{debug}
	and warn "Debug - GET $source: ", $rslt->status_line(), "\n";
    $rslt->is_success()
	or die "Failed to get $source data: ", $rslt->status_line();
    my $last_mod = last_modified( $source, $rslt );
    defined $last_mod
	and $last_mod > $date
	and $date = $last_mod;
    foreach my $line ( split qr{ \n }smx, $rslt->content() ) {
	$line =~ m/ \A ( [0-9]{5} ) /smx
	    or next;
	chomp $line;
	$process->( "$1", $line );
    }
    return;
}

sub unpack_mag {
    my ( $line ) = @_;
    49 > length $line
	and $line = sprintf '%-49s', $line;
    my ( undef, $mag ) = unpack 'a5x32a5', $line;
    $mag =~ s/ \s+ //smxg;
    '' eq $mag
	and return;
    return $mag;
}
__END__

=head1 TITLE

visual - Compare Celestrak visual to McCants vsnames

=head1 SYNOPSIS

 visual
 visual -help
 visual -version

=head1 OPTIONS

=head2 -debug

If asserted, this Boolean option causes debug information to be written
to standard error. Asserting this option is unsupported, at least in the
sense that the author reserves the right to change the output without
notice.

=head2 -decayed

If this Boolean option is asserted,
L<Astro::SpaceTrack|Astro::SpaceTrack> and L<JSON|JSON> are loaded, and
the Space Track web site is queried for the Satcat status of the
objects. Any that have defined decay dates are eliminated.

=head2 -help

This option displays the documentation for this script. The script then
exits.

=head2 -merge

If asserted, this option causes Mike McCants' quicksat.mag file to be
fetched also, and a magnitude hash to be produced that defines
magnitudes for any body that appears on either the Celestrak visual list
or the McCants vsnames list, and has a magnitude in either the McCants
vsnames list or the McCants quicksat list. The output is Data::Dumper
format.

=head2 -version

This option displays the version of this script. The script then exits.

=head1 DETAILS

This Perl script downloads the list of visual bodies from the Celestrak
web site and the vsnames.mag file from Mike McCants' web site and
compares the two, reporting OIDs that are not on both sites and what
site they B<are> on.

Note, though, that you get different output if you assert C<-merge>.

In either case, though, the last thing you get is a C<Last-Modified:>
date, which is the most-recent of any of the data sources examined.

=head1 AUTHOR

Thomas R. Wyant, III F<wyant at cpan dot org>

=head1 COPYRIGHT AND LICENSE

Copyright (C) 2014-2019 by Thomas R. Wyant, III

This program is free software; you can redistribute it and/or modify it
under the same terms as Perl 5.10.0. For more details, see the Artistic
License 1.0 at
L<https://www.perlfoundation.org/artistic-license-10.html>, and/or the
Gnu GPL at L<http://www.gnu.org/licenses/old-licenses/gpl-1.0.txt>.

This program is distributed in the hope that it will be useful, but
without any warranty; without even the implied warranty of
merchantability or fitness for a particular purpose.

=cut

# ex: set textwidth=72 :