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

#
# Remove an IP address (or a complete host) from the Netmagis database
#
# Syntax:
#   dnsdelip <ip> <view>
#
# History
#   2004/10/01 : pda/jean : design
#   2007/10/25 : jean     : log modify actions
#   2010/12/18 : pda      : use new install system
#   2013/04/05 : pda/jean : add views
#

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

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

proc syntax-error {argv0} {
    regsub {.*/} $argv0 {} argv0
    return "usage: $argv0 ip 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 addr view

    #
    # 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]
    }

    #
    # IP address validation
    #

    set msg [check-ip-syntax $dbfd $addr "inet"]
    if {$msg ne ""} then {
	d error $msg
    }

    #
    # Check access to address
    #

    if {! [check-authorized-ip $dbfd $tabcor(idcor) $addr]} then {
	d error [mc "You don't have rights on '%s'" $addr]
    }

    #
    # Does the IP address exist?
    #

    if {! [read-rr-by-ip $dbfd $addr $idview trr]} then {
	d error [mc "Address '%s' not found" $addr]
    }

    #
    # Check access to host
    #

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

    #
    # Process to the removal
    #

    d dblock {}

    set msg [del-ip $dbfd $addr trr $idview delobj]
    # delobj (deleted object: address or host name) is ignored in return
    if {$msg ne ""} then {
	d error [d dbabort "delete" $msg]
    }
    d dbcommit "delete"

    #
    # End
    #

    d end
    return 0
}

exit [main $argv0 $argv]
