/*
 * Copyright (c) 2009-2012 Zmanda, Inc.  All Rights Reserved.
 * Copyright (c) 2013-2016 Carbonite, Inc.  All Rights Reserved.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
 *
 * Contact information: Carbonite Inc., 756 N Pastoria Ave
 * Sunnyvale, CA 94085, or: http://www.zmanda.com
 */

%perlcode %{

=head1 NAME

Amanda::Config - access to Amanda configuration parameters

=head1 SYNOPSIS

    use Amanda::Config qw( :init :getconf );

    my $config_name = shift @ARGV;
    config_init($CONFIG_INIT_EXPLICIT_NAME, $config_name);
    apply_config_overrides($config_overrides);
    my ($cfgerr_level, @cfgerr_errors) = config_errors();
    if ($cfgerr_level >= $CFGERR_WARNINGS) {
	config_print_errors();
	if ($cfgerr_level >= $CFGERR_ERRORS) {
	    die("errors processing config file");
	}
    }

    print "tape device is ", getconf($CNF_TAPEDEV), "\n";

This API closely parallels the C API.

=head1 INITIALIZATION

The Amanda configuration is treated as a global state for the
application.  It is not possible to load two configurations
simultaneously.

All initialization-related symbols can be imported with the tag
C<:init>.

=head2 LOADING CONFIGURATION

The Amanda configuration is loaded with the aptly named
C<config_init($flags, $name)>.  Because of the great variety in
invocation method among Amanda applications, this function has a number
of flags that affect its behavior.  These flags can be OR'd together.

=over

=item If C<CONFIG_INIT_EXPLICIT_NAME> is given, then the C<$name> parameter can
contain the name of a configuration to load.  Note that if the parameter is
C<".">, this is equivalent to C<CONFIG_INIT_USE_CWD>.

=item If C<CONFIG_INIT_USE_CWD> is given, and if the current directory
contains C<amanda.conf>, then that file is loaded.

=item If C<CONFIG_INIT_CLIENT> is given, then a client configuration
is loaded.

=item If C<CONFIG_INIT_OVERLAY> is given, then any existing
configuration is not reset.

=back

See C<conffile.h> for more detailed information on these flags and
their interactions.

C<config_uninit()> reverses the effects of C<config_init>.  It is
not often used.

Once the configuration is loaded, the configuration name
(e.g., "DailySet1"), directory (C</etc/amanda/DailySet1>),
and filename (C</etc/amanda/DailySet1/amanda.conf>) are
available from C<get_config_name()>, C<get_config_dir()>, and
C<get_config_filename()>, respectively.

=head3 CONFIG ERRORS

This module collects configuration errors and warnings in a list, and also
tracks the overall error level with an enumeration: C<$CFGERR_OK>,
C<$CFGERR_WARNINGS>, and C<$CFGERR_ERRORS>.  C<config_init> and
C<apply_config_overrides> both return the current level.  The level and the
list of error messages are available from C<config_errors>:

  my ($cfgerr_level, @errors) = Amanda::Config::config_errors();

As a convenience, C<config_print_errors> will print all error messages to
stderr.  The error state can be cleared with C<config_clear_errors>.

=head2 CONFIG OVERWRITES

Most Amanda applications accept the command-line option C<-o>
to "overwrite" configuration values in C<amanda.conf>.  In Perl
applications, these options should be parsed with L<Getopt::Long|Getopt::Long>, with
the action being a call to C<add_config_override_opt>.  For example:

  my $config_overrides = new_config_overrides($#ARGV+1);
    GetOptions(
	# ...
	'o=s' => sub { add_config_override_opt($config_overrides, $_[1]); },
    ) or usage();
  my $cfg_ok = config_init($CONFIG_INIT_EXPLICIT_NAME | $CONFIG_INIT_USE_CWD, $config_name);
  apply_config_overrides($config_overrides);

C<new_config_overrides($size_estimate)> creates a new
overwrites object, using the given size as an estimate of
the number of items it will contain (C<$#ARGC/2> is a good
estimate).  Individual configuration options are then added via
C<add_config_override($co, $key, $value)> (which takes a key/value
pair) or C<add_config_override_opt($co, $optarg)>, which parses a
string following C<-o> on the command line.

Once the overwrites are gathered, they are applied with
C<apply_config_overrides($co)>, which applies the overwrites to the
active configuration.  No further operations can be performed on the
overwrites object after C<apply_config_overrides> has been called.

The utility function C<get_config_options()> returns a list of
command-line arguments to represent any overwrites that were used
to generate the current configuration.  (TODO: this function isn't
available yet)

=head1 PARAMETER ACCESS

Amanda configurations consist of "global" parameters and several
sets of "subsections" -- one set for dumptypes, one for tapetypes,
and so on.

All of the global parameters are represented by a constant beginning with
C<$CNF_>, e.g., C<$CNF_LABELSTR>.  The function C<getconf($cnf)> returns the
value of parameter C<$cnf>, in whatever format is appropriate for the parameter
(see DATA FORMATS, below).  C<getconf_seen($cnf)> returns a true value if
C<$cnf> was seen in the configuration file.  If it was not seen, then it will
have its default value.  C<getconf_linenum($cnf)> returns the line number in
the configuration file where it is set, 0 if it is not in a configuration file,
or -2 if it is set in a command line argument.

Some parameters have enumerated types.  The values for those
enumerations are available from this module with the same name as
in C<conffile.h>.  For example, C<$CNF_TAPERALGO> will yield a value
from the enumeration C<taperalgo_t>, the constants for which all
begin with C<$ALGO_>.  See C<conffile.h> for the details.

Each subsection type C<TYP> has the following functions:

=over

=item C<lookup_TYP($subsec_name)>

which returns an opaque object
(C<$ss>) representing the subsection, or C<undef> if no subsection
with that name exists;

=item C<TYP_name($ss)>

returning the name of the subsection;

=item C<TYP_getconf($ss, $cnf)>

which fetches a parameter value from C<$ss>; and

=item C<TYP_seen($ss, $cnf)>

which returns a true value if <$cnf> was seen in the subsection.

=back

The subsections are:

=over

=item C<tapetype>

with constants beginning with C<$TAPETYPE_>

=item C<dumptype>

with constants beginning with C<$DUMPTYPE_>

=item C<interface>

with constants beginning with C<$INTER_>

=item C<holdingdisk>

with constants beginning with C<$HOLDING_>

=item C<application>

with constants beginning with C<$APPLICATION_>

=item C<script>

with constants beginning with C<$PP_SCRIPT_>

=item C<device>

with constants beginning with C<$DEVICE_CONFIG_>.

=item C<changer>

with constants beginning with C<$CHANGER_CONFIG_>.

=back

See C<conffile.h> for the names of the constants themselves.

=head2 DATA FORMATS

Each configuration parameter has a "conftype", as assigned in
C<common-src/conffile.c>.  The translation of most of these types into Perl
values is straightforward:

  CONFTYPE_INT                        Math::BigInt
  CONFTYPE_INT64                      Math::BigInt
  CONFTYPE_REAL                       floating-point value
  CONFTYPE_STR                        string
  CONFTYPE_IDENT                      string
  CONFTYPE_TIME                       Math::BigInt (epoch value)
  CONFTYPE_SIZE                       Math::BigInt
  CONFTYPE_BOOLEAN                    Math::BigInt
  CONFTYPE_COMPRESS                   Math::BigInt
  CONFTYPE_ENCRYPT                    Math::BigInt
  CONFTYPE_HOLDING                    Math::BigInt
  CONFTYPE_ESTIMATELIST               [ Math::BigInt, .. ]
  CONFTYPE_STRATEGY                   Math::BigInt
  CONFTYPE_TAPERALGO                  Math::BigInt
  CONFTYPE_PRIORITY                   Math::BigInt
  CONFTYPE_RATE                       float, float
  CONFTYPE_INTRANGE                   Math::BigInt, Math::BigInt
  CONFTYPE_APPLICATION                string
  CONFTYPE_EXECUTE_ON                 string
  CONFTYPE_EXECUTE_WHERE              Math::BigInt
  CONFTYPE_SEND_AMREPORT_ON           Math::BigInt
  CONFTYPE_IDENTLIST                  [ string, .. ]
  CONFTYPE_PART_CACHE_TYPE	      Math::BigInt
  CONFTYPE_RECOVERY_LIMIT             [ string, .. ] (undef if not specified;
					    undef in the list means same-host)

Note that C<CONFTYPE_INTRANGE> and C<CONFTYPE_RATE> each return two values, not
an array reference.

Include and exclude lists with type C<CONFTYPE_EXINCLUDE> return a hash giving
all listed filenames (in the C<list> key), include/exclude files (C<files>),
and a boolean indicating that the list is optional (C<optional>):

  { list => [ str, .. ], file => [ str, .. ], optional => Math::BigInt }

Properties are represented as a hash of hashes.  The keys are the property
names, converted to ASCII lowercase.  Each property has a C<values> array
giving all values specified for this property, as well as booleans C<priority>
and C<append> that are true if the corresponding keyword was supplied.

  { prop1 => { values => [ str, .. ] priority => int, append => int },
    prop2 => { .. } .. }

Note that integer types of all sizes become C<Math::BigInt> objects rather than
Perl integers, as is the habit throughout Amanda.

The C<CNF_AUTOLABEL> value is a hash with the following keys

  template	label template, or undef
  other_config	boolean
  non_amanda	boolean
  volume_error	boolean
  empty		boolean

=head2 OTHER ACCESS

Parameter values are available by name from C<getconf_byname($name)> and
C<getconf_byname_strs($name, $str_needs_quotes)>.  These functions implement
the C<TYP:NAME:PARAM> syntax advertised by C<amgetconf> to access values in
subsections.  The first function returns a Perl value (see DATA FORMATS,
above), while the second returns a list of strings suitable for use in
C<amanda.conf>, including quotes around strings if C<$str_needs_quotes> is
true.

C<getconf_list($typ)> returns a list of the names of all subsections of the
given type.  C<%subsection_names> is a hash whose keys are allowed subsection
names.

=head2 DERIVED VALUES

The C<$CNF_DISPLAYUNIT> implies a certain divisor to convert from
kilobytes to the desired unit.  This divisor is available from
C<getconf_unit_divisor()>.  Note carefully that it is a I<divisor>
for a value in I<kilobytes>!

Finally, various subsections of Amanda enable verbose debugging via
configuration parameters.  The status of each parameter is available
a similarly-named variable, e.g., C<$debug_auth>.

All parameter access functions and constants can be imported with
the tag C<:getconf>.

=head1 MISCELLANEOUS

These functions defy categorization.

The function C<config_dir_relative> will interpret a path relative to
the current configuration directory.  Absolute paths are passed through
unchanged, while relative paths are converted to absolute paths.

C<dump_configuration()> dumps the current configuration, in a format
suitable for re-evaluation for this module, to standard output.
This function may be revised to return a string.

Several parts of Amanda need to convert unit modifier value like
"gbytes" to a multiplier.  The function C<find_multiplier($str)>
returns the unit multiplier for such a string.  For example, "mbytes"
is converted to 1048576 (1024*1024).

C<string_to_boolean()> takes a string and returns 0 if it matches any of
Amanda's names for false, or 1 if matches a name for true. If it can't be
interpreted, C<undef> is returned.

C<amandaify_property_name()> converts a string into Amanda's property style:
all lower-case and with "-" replacing "_".

=head1 CONSTANTS

This section lists all of the configuration parameter constants defined in this
module.  All of these constants are available with the C<:getconf> export tag.

=cut

%}
