#!/usr/bin/perl

open (STDERR, ">&STDOUT");
select ((select(STDOUT), $| = 1)[0]); # Synchronize STDOUT
select ((select(STDERR), $| = 1)[0]); # with STDERR

($dns_lib = $0) =~ s:(^|/)[^/]*$::;
($script=$0) =~ s:^.*/([^/]*)$:$1:;	# Get the simple name of this script.

push (@INC, $dns_lib);

require 5.0;
require 'dns_lib.perl';

use Getopt::Long;
$Getopt::Long::autoabbrev=1;    # Allow keyword abbreviations (to uniqueness).
$Getopt::Long::getopt_compat=1; # Allow both "--foo=bar" and "+foo=bar" style.
#$Getopt::Long::option_start='(--|-|\+)';       # [Use the defaults]
#$Getopt::Long::order=$Getopt::Long::REQUIRE_ORDER; # Options can't intermingle
$Getopt::Long::order=$Getopt::Long::PERMUTE;    # or options may intermingle.
$Getopt::Long::ignorecase=1;    # Don't consider case in options.
$Getopt::Long::debug=0;         ### Debug ###

$opt_help = ($#ARGV < 0);

&GetOptions ('help') || die "\nTry: $script --help for more information.\n\n";

if ($opt_help) { 
 
    print <<"EndOfHelp";
Usage: $script [OPTION] host pref ip
 
  --help   This page.

  host     The fully qualified DNS name of the host you want to remove
           an MX record from.
  pref     The preference value of the MX record you want to remove.
  server   The server the MX record points at.
 
EndOfHelp
    
    exit;

} # End if - help

$name = $ARGV[0];

if (! $name) {

    die "\nError.  Try: $script --help for more information.\n\n";

} else {

    $name = &verify_name ($name);

}

$pref = $ARGV[1];

if ((! $pref) || ($pref < 0) || ($pref > 65535)) {

    die "\nError.  Try: $script --help for more information.\n\n";

}

$server = $ARGV[2];

if (! $server) {

    die "\nError: There are illegal chars in the server argument or it wasn't entered.\n\n";

} else {

    $server = &verify_name ($server);

}

if ((($x = &verify_zone ($name)) eq 'PRIMARY') || ($x eq 'SEC_W_GLUE')) {

    $host = '@';
    $zone = $name;

} else {

    ($host, $zone) = split ('\.', $name, 2);
    die "Error: Cannot remove MX for $host from $zone -- no .primary file, use new_primary.\n" unless (($x = &verify_zone ($zone)) eq 'PRIMARY') || ($x eq 'SEC_W_GLUE');

}

&rcs_co ($zone, '.primary');
@file = &read_file ($zone, '.primary');
$record = &build_record ($host, 'MX', $pref, $server);
@recs = &find_record ($record, @file);

if ($#recs < 0) {

    $output = "\nError: No matching record.\nTry show_primary $zone\n";

} else {

    ($result, @file) = &remove_record ($record, @file);

    if ($result eq 'REMOVED') {

	&write_file ($zone, '.primary', @file);
	$output = "\nRecord Removed: MX for $host removed from $zone\n";
	$change = 1;

    } else {

	$output = "\nError: This isn't supposed to happen...\n";
	
    }

}

&rcs_ci ($zone, '.primary', "Script $script: removed MX record for $host", $change);
print "$output\n";

exit;

