package NamedConf;

use Conf;
use Errors;
use ZoneEntry;

BEGIN {
    @Conf::Ids = (@Conf::Ids, '$Header: /afs/sipb.mit.edu/project/zoned/src/RCS/NamedConf.pm,v 1.3 2005/06/28 01:28:42 jweiss Exp $ ');
};

return 1;

# Generates a named.conf file from the manual portion of named.conf, 
#   and a given collection of zone entries.
# A collection of warning text is stuck in as well.
sub named_conf {
    my $zesref = shift;

    if (!open(MANUAL, $Conf::named_manual)) {
	die("Could not open hand-written conf file $Conf::named_manual: $!\n");
    }
    
    my $manual = join('', <MANUAL>);

    close(MANUAL);

    my $genstanzas = join("\n", map {named_stanza($_)} @{$zesref});

    my $out = "// !!! DO NOT EDIT THIS FILE !!!\n";
    $out .= "// It is automatically generated by zoned\n";
    $out .= "// Hand-edited portions are taken from $Conf::named_manual\n";
    $out .= "// It also includes stanzas produced from $Conf::zonelist\n";
    $out .= "// You want to change one of these rather than this file\n\n";

    $out .= "// BEGIN $Conf::named_manual\n";
    $out .= $manual;
    $out .= "\n//END $Conf::named_manual\n";

    $out .= "\n\n// AUTOMATICALLY-GENERATED ZONE STANZAS\n";
    $out .= "// Generated " . localtime(time()) . "\n";

    $out .= $genstanzas;

    return $out;
}

# Generates a named.conf "stanza" for a given ZoneEntry
sub named_stanza {
    my $ze = shift;
    
    my $stanza = "zone \"" . $ze->zone() . "\" {\n";
    if ($ze->is_master()) {
	$stanza .= "\ttype master;\n";
	$stanza .= "\tfile \"" . Conf::filepath($ze->zonefile()) . "\";\n";
    } else {
	$stanza .= "\ttype slave;\n";
	$stanza .= "\tfile \"$Conf::named_cache_dir/"
	    . $ze->zonefile() . "\";\n";
	$stanza .= "\tmasters {\n";
	foreach my $master ($ze->masters()) {
	    $stanza .= "\t\t$master;\n";
	}
	$stanza .= "\t};\n";
    }

    $stanza .= "};\n";

    return $stanza;
}

