#!/usr/bin/perl
# Put a DNS record in RFC1035 format
# The script takes a single argument which is a an RFC1034 format DNS entry
#

$debug=0;

die "Wrong number of arguments $#ARGV to put-dns\n" unless $#ARGV==0;

$zone = `crudini --get /etc/put-dns/put-dns.conf main domain`;
chomp($zone);
$record = $ARGV[0];


# print "zone is $zone\n";
# print "record is $record\n";


@elements = split /\s+/, $ARGV[0], 3;

$host = @elements[0];

$type = @elements[1];

$rdata = @elements[2];

# print "rdata is $rdata\n";

if ( $type eq "IN" ) {
	#	print "type was IN\n";
	($type,$rdata) = split /\s+/, @elements[2], 2;
}

# print "host is $host\n";
# print "type is $type\n";
# print "rdata is $rdata\n";

# First special case - put a record into the root of the zone
#

if ( $host eq "@" ) {
	# print "put something into the root of the zone\n";
	# sanity check - only do this for record types we know
	#
	if ( $type eq "TXT" ) {
		#
		#$command = "curl -v  --netrc-file /etc/sos/private/mythic-beasts-api -X POST https://api.mythic-beasts.com/dns/v2/zones/$zone/records -d host=@ -d type=TXT -d \"data=$rdata\"";
		# Try not putting data in quotes, as it is already quoted
		$command = "curl -v  --netrc-file /etc/sos/private/mythic-beasts-api -X POST https://api.mythic-beasts.com/dns/v2/zones/$zone/records -d host=@ -d type=TXT -d data=$rdata";
		# print "about to do $command\n";
		system($command);
	} elsif ( $type eq "MX" ) {
		# print "about to do an MX record\n";
		($priority,$mxdata) = split /\s+/, $rdata, 2;
		$command = "curl -v  --netrc-file /etc/sos/private/mythic-beasts-api -X POST https://api.mythic-beasts.com/dns/v2/zones/$zone/records -d host=@ -d type=MX -d mx_priority=$priority -d data=$mxdata";
		# print "about to do $command\n";
		system($command);
	} else {
		die "unknown type $type attemting to be added to root zone with data $rdata\n";
	}
	} else {
	        if ( $type eq "TXT" ) {
		    #
		    $command = "echo '$record' | curl -v  --netrc-file /etc/sos/private/mythic-beasts-api -X POST --data-binary \@- -H \"Content-Type: text/dns\" https://api.mythic-beasts.com/dns/v2/zones/$zone/records/$host/$type";
		    print "Put TXT record $record\n for host $host with **$command**\n" if ( $debug);
		    system($command);
	    } elsif ( $tyoe eq "SRV" )  {
	            print "SRV record - not handled yet - data was $rdata\n";
	    } else {
		 print "unknown type $type - not handled yet with data $rdata\n";
	 }	 

	}


