#!/usr/bin/perl

use strict;
use warnings;
use open ':std', ':encoding(UTF-8)';

use JSON::XS;
use FileHandle;
use Capture::Tiny(qw/:all/);
use Text::CSV::Easy(qw/csv_build csv_parse/);

## get the hosted zone info
my $awsResult = capture { system "aws route53 list-hosted-zones-by-name" }
  or die "AWS list hosted zone didn't work check syntax or perms";

my $hostedZone   = JSON::XS::decode_json($awsResult);
my $hostedZoneId = $hostedZone->{'HostedZones'}->[0]->{'Id'};

my $awsAction = {
    'Action'            => 'UPSERT',
    'ResourceRecordSet' => {
        'Name'            => undef,
        'ResourceRecords' => [],
        'TTL'             => 300,
        'Type'            => 'A',
    }
};
my $awsActionJSON = JSON::XS::encode_json($awsAction);
my $jsonxs = JSON::XS->new->ascii->pretty->allow_nonref;

my $changes;
open F, shift @ARGV;
while (<F>) {
	next if /^#/;
    my ( $ip, $hostname ) = csv_parse($_);
    my $href = JSON::XS::decode_json($awsActionJSON);
    my $value = { 'Value' => $ip };
    $href->{'ResourceRecordSet'}->{'Name'} = $hostname.'.royaltyshare.dev';
    push @{ $href->{'ResourceRecordSet'}->{'ResourceRecords'} }, $value;
    push @{ $changes->{'Changes'} }, $href;
}
close F;
my $json = $jsonxs->encode($changes);
print "$json\n";
