#!/usr/local/bin/tclsh8.6

#
# Remove a name (host or alias) from the Netmagis database
#
# Syntax:
#   dnsdelhost <fqdn> <view>
#
# History
#   2004/10/01 : pda/jean : design
#   2007/10/25 : jean     : log modify actions
#   2010/12/18 : pda      : use new install system
#   2013/03/28 : pda/jean : add views
#

source /usr/local/lib/netmagis/libnetmagis.tcl

##############################################################################
# Small utility functions
##############################################################################

proc syntax-error {argv0} {
    regsub {.*/} $argv0 {} argv0
    return "usage: $argv0 fqdn view"
}

##############################################################################
# Main program
##############################################################################

proc main {argv0 argv} {
    global conf

    #
    # Initialization
    #

    set msg [d init-script dbfd $argv0 false tabcor]
    if {$msg ne ""} then {
	d error $msg
    }

    #
    # Argument checking
    #

    if {[llength $argv] != 2} then {
	d error [syntax-error $argv0]
    }
    lassign $argv fqdn view
    set fqdn [string tolower $fqdn]

    #
    # Check access to view
    #

    set idview [u viewid $view]
    if {$idview == -1} then {
	d error [mc "Invalid view '%s'" $view]
    }
    if {! [u isallowedview $idview]} then {
	d error [mc "Access denied to view '%s'" $view]
    }

    #
    # Host name validation
    #

    set msg [check-fqdn-syntax $dbfd $fqdn name domain iddom]
    if {$msg ne ""} then {
	d error $msg
    }
    set name [string tolower $name]

    #
    # Check access to name
    #

    set msg [check-authorized-host $dbfd $tabcor(idcor) $name $domain $idview trr "del-name"]
    if {$msg ne ""} then {
	d error $msg
    }

    #
    # Does the name exist and is an host or an alias in this view?
    #

    set exists 0
    if {$trr(idrr) ne ""} then {
	if {[llength [rr-ip-by-view trr $idview]] > 0} then {
	    set exists 1
	} elseif {[llength [rr-cname-by-view trr $idview]] > 0} then {
	    set exists 1
	}
    }
    if {! $exists} then {
	d error [mc "Name '%s' does not exist" "$name.$domain"]
    }

    #
    # Process to the removal
    #

    d dblock {}

    set msg [del-host $dbfd trr $idview]
    if {$msg ne ""} then {
	d error [d dbabort "delete" $msg]
    }
    d dbcommit "delete"

    #
    # End
    #

    d end
    return 0
}

exit [main $argv0 $argv]
