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

#
# Write zone prologue to database (from file)
#
# Syntax:
#   dnswriteprol <zone> <view> <file>
#
# History
#   2004/05/25 : pda      : design with sh
#   2005/04/11 : pda      : rewriting with Tcl
#   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 zone view file"
}

##############################################################################
# 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 zone view file

    #
    # 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 that zone exists
    #

    set qzone [::pgsql::quote $zone]
    set sql "SELECT prologue FROM dns.zone
    				WHERE name = '$qzone' AND idview = $idview"

    set found 0
    pg_select $dbfd $sql tab {
	set old $tab(prologue)
	set found 1
    }

    if {! $found} then {
	d error [mc "Zone '%s' not found" $zone]
    }

    #
    # Get file contents
    #

    if {[catch {set fd [open $file "r"]} msg]} then {
	d error [mc {Cannot open file '%1$s': %2$s} $file $msg]
    }
    set new [read $fd]
    close $fd

    #
    # Tests
    #

    if {$new eq $old} then {
	puts stderr [mc "No difference. Zone '%s' not modified" $zone]
	return 0
    }

    #
    # Process modification
    #

    set txt [::pgsql::quote $new]
    set sql "UPDATE dns.zone SET prologue = '$txt'
    				WHERE name = '$qzone' AND idview = $idview"

    if {! [::pgsql::execsql $dbfd $sql msg]} then {
	return [mc "Cannot write zone prologue: %s" $msg]
    }

    #
    # Write log
    #

    d writelog "modref" "modification of reference table zone for '$zone'"

    #
    # End
    #

    d end
    return 0
}

exit [main $argv0 $argv]
