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

#
# Add an alias in Netmagis database
#
# Syntax :
#   dnsaddalias <fqdn-alias> <fqdn-host>
#
# History
#   2004/09/24 : pda/jean : design from cgi script
#   2005/04/11 : pda/jean : adaptation
#   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-alias fqdn-host 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] != 3} then {
	d error [syntax-error $argv0]
    }
    lassign $argv fqdnalias fqdnref 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]
    }

    #
    # Check alias FDQN
    #

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

    #
    # Check host FQDN
    #

    set msg [check-fqdn-syntax $dbfd $fqdnref nameref domainref iddomref]
    if {$msg ne ""} then {
	d error $msg
    }
    set nameref [string tolower $nameref]

    set msg [add-alias $dbfd $name $domain $idview \
    				$nameref $domainref $tabcor(idcor)]
    if {$msg ne ""} then {
	d error $msg
    }

    #
    # End
    #

    d end
    return 0
}

exit [main $argv0 $argv]
