#!/usr/bin/perl -w

#
# rssacint_to_magnitude_csv
#
# Copyright (C) 2025 University of Southern California.
# All rights reserved.                                            
#                                                                
# Redistribution and use in source and binary forms are permitted
# provided that the above copyright notice and this paragraph are
# duplicated in all such forms and that any documentation, advertising
# materials, and other materials related to such distribution and use
# acknowledge that the software was developed by the University of
# Southern California, Information Sciences Institute.  The name of the
# University may not be used to endorse or promote products derived from
# this software without specific prior written permission.
# 
# THIS SOFTWARE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED
# WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
# 



=head1 NAME

rssacint_to_magnitude_csv - convert rssacint to dns magnitude CSV-format input

=head1 SYNOPSIS

rssacfin_to_magnitude_csv < file.rssacfin > file.csv

=head1 DESCRIPTION

Reads rssacint format,
after it's been reduced but before IPs are counted (to rssacfin),
and converts it to DNS Magnitude CSV input (ip,tld,count).

(Basically, we pick out +ma and +mb records.
Although ma records are truncated to /64s
and Magnitude wants /48s, we let them do further truncation.)

We also suppress the trailing "." on domain names, because dnsmag
refuses to handle it.

=head1 OPTIONS

=over

=item B<-d>

Enable debugging output.

=item B<-v>

Enable verbose output.

=item B<--help>

Show help.

=item B<--man>

Show full manual.

=back

=cut

use strict;
use Pod::Usage;
use Getopt::Long;

Getopt::Long::Configure ("bundling");
pod2usage(2) if ($#ARGV >= 0 && $ARGV[0] eq '-?');
#my(@orig_argv) = @ARGV;
my($prog) = $0;
my $debug = undef;
my $verbose = undef;
&GetOptions(
 	'help|?' => sub { pod2usage(1); },
	'man' => sub { pod2usage(-verbose => 2); },
	'd|debug+' => \$debug,   
        'v|verbose+' => \$verbose) or pod2usage(2);
pod2usage("$prog: takes no arguments.\n") if ($#ARGV != -1);

print("#fsdb -F t ip tld count\n");
while(<>) {
    next if (/^#/);   # comments
    if (/^\+m([ab])([^:]+):([^\t]+)\t(\d+)$/) {
        # ipv4.  add the trailing 0
        my($type, $tld, $ip, $count) = ($1, $2, $3, $4);
        if ($type eq 'b') {
            $ip .= "0";
        } else {
            # ipv6 requires no modification; we assume it ends with ::
        };
        $tld =~ s/\"/\042/g;
        $tld =~ s/\,/\054/g;
        $tld =~ s/\.$//;
        print(join("\t", $ip, $tld, $count) . "\n");
    } else {
        # Nothing else is relevant.
    };
};


exit 0;

