#!/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 ip
 
  --help   This page.

  host     The fully qualified DNS name of the host you want to remove.
  ip       The IP address of the host you want to remove.
 
EndOfHelp
    
    exit;

} # End if - help

$host = $ARGV[0];

if (! $host) {

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

} else {

    $host = &verify_name ($host, '');

}

$ip = $ARGV[1];

if (! $ip) {

    die "\nYou must enter an IP address.  Try: $script --help for more information.\n\n";

} else {

    $ip = &verify_ip ($ip, '');

}

$zone = &reverse_ip ($ip) unless $ip =~ m/\.in-addr\.arpa\.?$/o;
($host_num, $zone) = split ('\.', $zone, 2);

die "\nWe are not primary for $zone.\nUse new_primary to create the zone.\n\n" unless (($x = &verify_zone ($zone)) eq 'PRIMARY') || ($x eq 'SEC_W_GLUE');

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

if ($#recs < 0) {

    $output = "\nError: No matching PTR record to remove.\n";

} else {

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

    if ($result eq 'REMOVED') {

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

    } else {

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

    }

}

&rcs_ci ($zone, '.primary', "Script $script: removed PTR record $host_num [$host]", $change);
print "$output\n";

exit;

