#!/bin/sh
# -*- perl -*-
# vim:set syn=perl:
#
# Zeus configuration management tool
#

###
### SHELL BOOTSTRAP
###

# Check for stand-alone version (overrides any ZEUSHOME)
if [ -d "`dirname $0`/resources" ]; then
   ZEUSHOME=`dirname $0`/resources/
   export ZEUSHOME
fi

# Ensure ZEUSHOME is setup to point to our installation
if [ -z "$ZEUSHOME" ]
then
    # Have a good guess, we expect to live in $ZEUSHOME/zxtm/bin
    OLD_PWD=`pwd`
    cd `dirname $0`/..
    cd ..
    if [ -d 'zxtm/bin' ]
    then
       ZEUSHOME=`pwd`
       export ZEUSHOME
       cd $OLD_PWD
    else
       echo "Broken installation: missing components."
       exit 1
    fi
fi

if [ ! -z "$ZEUSHOME" ]
then
   PROG=$ZEUSHOME/perl/miniperl
fi

exec $PROG -x $0 ${1+"$@"}
#!perl -w
#line 44

BEGIN {
   # make sure we have all the perl modules we need
   unshift( @INC, "$ENV{ZEUSHOME}/zxtmadmin/lib/perl",
            "$ENV{ZEUSHOME}/admin/lib/perl",
            "$ENV{ZEUSHOME}/zxtm/lib/perl",
            "$ENV{ZEUSHOME}/perl" );
}

use strict;
use warnings;
use Cwd;
use Zeus::ZXTM::Utils qw( copy_file pidRunning );
use Zeus::ZXTM::ConfManagement qw( ZEUS_VERSION_RE );
use Zeus::ZXTM::LocationUtils qw( locationKey );
use Zeus::Dumper;
use Zeus::Execute qw( execute );
use Zeus::Tar qw( tarAppend );
use Zeus::TarReader;
use Zeus::ConfigErrors qw( getErrors );
use Zeus::ZXTM::AFMUtils qw(
   $afm_config_archive
   AFMEnabledInConfig
   HandleSAF_BackupCreation
   HandleSAF_BackupRestore
   getAFMRESTStateMessage
   WaitForAFMRunning
);
use Zeus::ZXTM::AFMConfigure qw( GetAfmPortHash );

use POSIX qw(strftime);

sub safe_check_afm_enabled($);

my $ZEUS_VERSION_RE = ZEUS_VERSION_RE;

###
### COMMANDS
###

# This hash defines the commands the 'zconf' program understands.  The
# structure is:
#
# <command> => {
#     help => <helpful text>,
#     options => [ <list of --command-line-options> ],
#    }, ...
#
# The entries in the 'options' array will be printed in the order they appear
# in when help output is generated for the command.  The command line option
# details are read from the %options hash that follows %commands.
#
my %commands = (
   list => {
      usage => '[OPTION]... [SOURCE]...',
      help => <<'END',

The list command is a dependency-aware file-list generator for Stingray
configuration directories. If specified without any arguments it will list all
files in the current $ZEUSHOME/zxtm/conf directory. If given one or more SOURCE
arguments these will be used as the source for the listing. If a SOURCE is a
directory then all files in that directory will be listed (i.e. "vservers" will
list all virtual server configuration files), if a SOURCE is a file then that
file will be listed (i.e. "vservers/My VS").

Additionally, all files the listed SOURCEs depend on will also be listed. For
example the pool configuration and any rules and classes that "vservers/foo"
requires will be included. Then, any files the additional files depend on will
be included (i.e. the pool's monitors). This dependency resolving continues on
included dependencies until all dependencies are resolved.

The list is printed to standard output and consists of paths relative to the
top-level "conf" directory.

If a specified SOURCE does not exist in the configuration a warning will be
printed to standard error, but the processing of further arguments will
continue.

END
      options => [ '--confpath', '--assumeversion' ]
   },
   export => {
      usage => '[OPTION]... [SOURCE]...',
      help => <<'END',

Create a Stingray software configuration archive containing the specified
configuration SOURCEs and their dependencies.   Dependency resolution works as
described for the "list" command.  If no SOURCEs are specified the entire
configuration will be exported.

By default the archive data (in "tar" format) is printed to standard output.
Alternatively a --file OPTION can be specified providing a filename, the
exported configuration archive will be created using this filename.

END
      options => [
         '--confpath',
         '--exclude',
         '--version',
         '--description',
         '--file',
         '--dryrun'
      ],
   },
   "copy" => {
      usage => '[OPTION]... [SOURCE]...',
      help => <<'END',

Create a Stingray software configuration directory containing the specified
configuration SOURCEs and their dependencies.   Dependency resolution works as
described for the "list" command.  If no SOURCEs are specified the entire
configuration will be copied.

The output directory is always named "conf" and must not pre-exist.  By default
it will be located in the current working directory.

END
      options => [
         '--confpath',
         '--destdir',
         '--exclude',
         '--version',
         '--description'
      ],
   },
   "import" => {
      usage => '[OPTION]... SOURCE [TARGET]',
      help => <<'END',

Import the SOURCE configuration into the TARGET configuration.  By default
TARGET is $ZEUSHOME/zxtm/conf.

This effectively merges the SOURCE into the TARGET configuration following
precedence rules to determine what configuration files and keys to retain from
the TARGET.  It is intended that the destination would normally be the "conf"
directory of a running Stingray instance, however it may also be a copy of a 
Stingray software configuration.

END
      options => [
         '--include',
         '--sourceversion',
         '--targetversion',
         '--replicate',
         '--no-replicate',
         '--filter',
         '--no-filter',
         '--dryrun',
         '--no-verify',
      ],
   },
   "diff" => {
      usage => '[OPTION]... SOURCE [TARGET]',
      help => <<'END',

The "diff" command shows the changes that would be made by an "import" in a
format similar to a unified diff.  This command is useful for inspecting
changes prior to applying an import (see also the --dryrun option for the
'import' command.)

END
      options => [
         '--include',
         '--sourceversion',
         '--targetversion',
         '--no-filter',
         '--filter',
         '--no-verify',
        ],
   },
   "replicate" => {
      usage => '[ZEUSHOME]',
      help => <<'END',

The "replicate" command can be used to copy the configuration from one Stingray
software instance to others it is clustered with.  By default the TARGET is
$ZEUSHOME. This command can only be used with the ZEUSHOME of a live Stingray
software instance.

END
      options => []
   },
   "version" => {
      usage => '[ZEUSHOME]',
      help => <<'END',

The "version" command displays the version of the Stingray software installed at
ZEUSHOME.  By default ZEUSHOME uses the value of $ZEUSHOME.

END
      options => []
   },
   "info" => {
      usage => 'CONFPATH',
      help => <<'END',

The "info" command shows the configuration metadata from CONFPATH.  The
supplied CONFPATH must have been generated using the "export" or "copy"
commands.

END
      options => []
   },
   "getdefaultfilter" => {
      usage => '',
      help => <<'END',

The "getdefaultfilter" command prints the default filter specification to
standard output.  This could then be used as a template for a customised filter
configuration.

END
      options => []
   },
   "help" => {
      usage => '[COMMAND]',
      help => <<'END',

Use the 'help' command view helpful descriptions of zconf COMMANDs.

END
      options => []
   },
);

###
### OPTIONS
###

# The %options hash contains all the command line options that can be used with
# the commands above.  Option data consists of:
#
# hasarg:   whether or not the option has an argument
# onceonly: whether or not the option can be given multiple times
# check:    a basic check to apply to the argument, if any
# error:    error text to supply if the check fails
# help:     help text describing the option
#
my %options = (
   '--confpath' =>  {
      hasarg => 1,
      onceonly => 1,
         # argument is a readable and executable directory, or a readable file
      check => sub { (-d $_[0] && -r $_[0] && -x $_[0]) || (-f $_[0] && -r $_[0]) },
      error => "Argument to --confpath must be a valid Stingray configuration " .
               "archive or conf directory.",
      help => <<'END'

Supply the path to a Stingray software configuration tree or archive (the archive
must have been created by Stingray software.)

END
   },
   '--file' =>  {
      hasarg => 1,
      onceonly => 1,
      check => sub { 1 }, # checked at file creation time
      error => "",
      help => <<'END'

Supply the name of the file to create.  If the file already exists and is
writeable it will be overwritten.

END
   },
   '--destdir' =>  {
      hasarg => 1,
      onceonly => 1,
      check => sub { 1 }, # checked later
      error => "",
      help => <<'END'

Supply the name of the destination directory.

END
   },
   '--version' => {
      hasarg => 1,
      onceonly => 1,
         # format of a Zeus software version number
      check => sub { $_[0] =~ /$ZEUS_VERSION_RE/; },
      error => "Argument to --version must be a valid Stingray version number.",
      help => <<'END'

Supply the Stingray software version.  Use this when working with configuration
directories that are outside of a Stingray software install and lack a VERSION_n
file.

END
   },
   '--description' => {
      hasarg => 1,
      onceonly => 1,
      check => sub { 1 }, # freeform text
      error => undef,
      help => <<'END'

Supply a description for the configuration.  The description is free-form text
and it will be placed in a file named DESCRIPTION in the root of the archived or
copied configuration.

END
   },
   '--include' => {
      hasarg => 1,
      onceonly => 0,
      check => sub { 1 }, # can't check until we read the configuration
      error => undef,
      help => <<'END'

Specify files to import to the target configuration.  This permits selected
components of a configuration copy or archive to be applied to a destination
configuration.  Dependencies will be resolved and included, if they exist in the
source, as per the 'export' command.  This, for example, means you can copy
selected configuration between two full configurations without the need to go
via the 'copy' or 'export' commands.

END
   },
   '--exclude' => {
      hasarg => 1,
      onceonly => 0,
      check => sub { 1 }, # has to be a file or directory within the
      error => undef,     # conf tree, this will be checked later
      help => <<'END'

Specify files to exclude from the destination archive or copy.  The argument
should be either a specific configuration file or a configuration directory.  In
the latter case no files in that directory will be included.  If there is a
direct conflict between the paths specified to be included and those excluded,
or an excluded path does not exist in the source configuration, a warning will
be printed to standard error.  Paths specified are relative to the root of the
configuration.

END
   },
   '--replicate' => {
      hasarg => 0,
      onceonly => 1,
      help => <<'END'

When applying configuration changes to a configuration tree use this argument to
tell zconf to try and find a running Stingray software instance associated with the
target configuration and instruct it to replicate changes across the cluster it
is in.  Note that if the target is not specified (i.e. the default, $ZEUSHOME,
is used) then --replicate is enabled automatically.

END
   },
   '--no-replicate' => {
      hasarg => 0,
      onceonly => 1,
      help => <<'END'

Do not replicate configuration changes across the cluster.  This can be used to
disable configuration replication when working with a live installation (i.e.
one that is located within your $ZEUSHOME).  See help for --replicate.

END
   },
   '--no-filter' => {
      hasarg => 0,
      onceonly => 1,
      help => <<'END'

The import will use a built-in filter by default.  The built-in filter is
designed to not apply machine-specific configuration to the target.  If you
want to import the full configuration you can disable filtering entirely using
this option.

END
   },
   '--filter' => {
      hasarg => 1,
      onceonly => 1,
         # the filter must be a readable file
      check => sub { -f $_[0] && -r $_[0] },
      error => "Argument to --filter must be a readable file",
      help => <<'END'

Specify a filter to use instead of the built-in filter.  The argument is a file
that contains the filter specification, such as the output of the
getdefaultfilter command.

A filter specification file contains lines of the form: <file-glob>[!<key-glob>]

The <file-glob> part is mandatory and can match either a file or a directory.
The match is an exact match of an entire path, an asterisk (*) at the beginning
or end of a path can be used to match partial paths.  For example "vservers"
will match the vservers directory and thus filter out all vserver configuration
files, this is synonymous with "vservers/" and "vservers/*".  If you want to
filter out all files called "myservice" you could specify "*/myservice", this
could be useful when you give your linked vservers and pools identical names.  A
single asterisk (*) on its own will match all configuration files (i.e. the
asterisk wildcard spans directory separators.) An entry of "pools/*http*" will
match all pools with the string "http" in their name.  Finally, note that
matching of file-names is case-sensitive.

The !<key-glob> part of the filter specification is optional, if no key part is
given then the whole file matching the <file-glob> will not be imported to the
target.  If they key part is included then only keys matching the glob will be
imported.  As with the <file-glob> the asterisk (*) wildcard can be used to
match multiple keys.

In both globs a literal asterisk can be matched by escaping the asterisk (*)
with a back-slash (\*), a literal exclamation mark (!) in a file-name also
(\!).  To match a back-slash use double-back-slash (\\), single back-slashes
in the globs will be removed with no effect in all other cases.

END
   },
   '--include' => {
      hasarg => 1,
      onceonly => 0,
      check => sub { 1 },
      error => undef,
      help => <<'END'

Rather than applying all configuration files from the source to the target you
can select specific source files using --include.  This can be specified
multiple times to include multiple sources.  Dependency resolution will be
performed and all dependencies will also be imported.

END
   },
   '--sourceversion' => {
      hasarg => 1,
      onceonly => 1,
         # format of a Zeus software version number
      check => sub { $_[0] =~ /$ZEUS_VERSION_RE/; },
      error => "Argument to --source-version must be a valid Stingray version number.",
      help => <<'END'

If the source configuration does not have a version file or associated Stingray
software install you can provide the version with this option.

END
   },
   '--targetversion' => {
      hasarg => 1,
      onceonly => 1,
         # format of a Zeus software version number
      check => sub { $_[0] =~ /$ZEUS_VERSION_RE/; },
      error => "Argument to --target-version must be a valid Stingray version number.",
      help => <<'END'

If the destination configuration does not have a version file or associated
Stingray software install you can provide the version with this option.

END
   },
   '--dryrun' => {
      hasarg => 0,
      onceonly => 1,
      help => <<'END'

Describe what the operation would do but do not commit the changes.

END
   },
   '--no-verify' => {
      hasarg => 0,
      onceonly => 1,
      help => <<'END'

Disable configuration consistency verification.

END
   },
   '--assumeversion' => {
      hasarg => 0,
      onceonly => 1,
      help => <<'END'

Assume the configuration being listed is from the same software version as the
zconf tool.  Use this if working with 'conf' directories or tar archives that
were not created by Stingray software (and don't contain the top-level
VERSION_<version> file.)

END
   },
);

###
### SETUP
###

my $confpath = "$ENV{ZEUSHOME}/zxtm/conf";
my $verbosity = 1;
my @haveargs;
my %haveopts;
my $command;

# set up wrap(...) function
my ($pad, $prepad, $wrap, $havewrap);
eval 'use Text::Wrap;';
if (not $@) {
   $havewrap = 1;
   use Text::Wrap;
   $wrap = *wrap;
   $Text::Wrap::unexpand = 0;

   my $columns;
   if (exists $ENV{COLS} and $ENV{COLS}) {
      $columns = $ENV{COLS};
   } elsif ((`tput cols 2>/dev/null`||"") =~ /(\d+)/) {
      $columns = $1;
   } elsif ((`stty -a 2>/dev/null`||"") =~ /columns(?:\s+|\s*[=:]\s*)(\d+)/) {
      $columns = $1;
   }
   $columns = 80 if not $columns;
   $columns = 20 if $columns < 20;
   $pad = 3;
   if ($columns > 80) {
      $columns -= 14;
      $pad = 7;
   }
   $Text::Wrap::columns = $columns;
   $prepad = sprintf('%*s', $pad+2, '');
   $pad = sprintf('%*s', $pad, '');
} else {
   $wrap = sub { shift; shift; return shift };
   ($pad, $prepad) = (" ", "  ");
}

###
### HELPER FUNCTIONS
###

sub exclusionMatch($$) {
   my ($exclusions, $file) = @_;
   my @parts = split( '/', $file );
   while (@parts) {
      $file = join( '/', @parts );
      if ( exists $exclusions->{$file} ) {
         $exclusions->{$file} = 0;
         return 1;
      }
      pop @parts;
   }
   return 0;
}

# expand a path starting with a ~ to a full path
sub deTilde($) {
   my $path = shift;
   # following code is from the perl cookbook
   $path =~ s{ ^ ~ ( [^/]* ) }{
      $1 ? (getpwnam($1))[7] :
         ( $ENV{HOME} || $ENV{LOGDIR} || (getpwuid($>))[7] )
     }ex;
   return $path;
}


# print a formatted error message
sub error($) {
   printf STDERR "%s\n", $wrap->("", $pad, "ERROR: " . shift);
}


# print a formatter warning message
sub warning($) {
   printf STDERR "%s\n", $wrap->("", $pad, "WARNING: " . shift);
}


# print runtime trace messages ($2), these will be printed if their level ($1)
# is higher than or equal to the current verbosity level (number of '-v's)
sub trace($$) {
   my ($level, $msg) = @_;
   if ($level < $verbosity) {
      printf STDERR "%*s%s\n", $level, "", $msg;
   }
}


# basic command-line help output
sub usage(;$)
{
   my( $ecode ) = shift;
   $ecode = 0 if not defined $ecode;

   print "Usage: $0 [COMMAND] [OPTIONS] [ARGUMENTS]\n";
   print STDOUT <<END;
Commands:

END

   for my $command (sort keys %commands) {
      print STDOUT "  $command\n";
   }

   print STDOUT <<END;

For more information on a given comment execute:

 $0 help <COMMAND>

END

   exit($ecode)
}


# print command usage then exit with code 1
sub dieWithUsage($)
{
   my( $msg ) = @_;

   $msg .= "\n" unless $msg =~ /\n/s;
   print STDERR "ERROR: $msg";
   print STDERR "\n";
   usage(1);

   exit 1;
}


sub help(;$); # defined later
# print the help output for a command then exit with code 1
sub dieWithHelp($$)
{
   my( $command, $msg ) = @_;

   $msg .= "\n" unless $msg =~ /\n/s;
   print STDERR "ERROR: $msg";
   print STDERR "\n";
   help($command);

   exit 1;
}

##
## PROCESS @ARGV
##
while (@ARGV) {
   my $arg = shift @ARGV;
   if ($arg eq '-v') {
      $verbosity++;
   } elsif ($arg eq '-q') {
      $verbosity--;
   } elsif ($arg eq '-h' or $arg eq '--help') {
      if (@ARGV > 0 or $command or keys %haveopts) {
         warning("The $arg option should appear on its own.");
      }
      $command = "help";
      last;
   } elsif ($arg =~ /^(--[^=]*)(?:=(.*))?$/) {
      my ($arg, $val) = ($1, $2);
      if (exists $options{$arg}) {
         if ($options{$arg}->{hasarg}) {
            if (not defined $val or $val eq "") {
               $val = shift;
            }
            if ($options{$arg}->{onceonly}) {
               $haveopts{$arg} = $val;
            } else {
               $haveopts{$arg} = [] if not exists $haveopts{$arg};
               push(@{$haveopts{$arg}}, $val);
            }
         } else {
            $haveopts{$arg} = 1;
         }
      } else {
         dieWithUsage("Unrecognised option: $arg");
      }
   } elsif (not $command) {
      if (exists $commands{$arg}) {
         $command = $arg;
      } else {
         dieWithUsage("Unknown command: $arg");
      }
   } else {
      push @haveargs, $arg;
   }
}
if (not $command) {
   dieWithUsage("No command specified.");
}
for my $opt (keys %haveopts) {
   if (not grep { /^$opt$/ } @{$commands{$command}->{options}}) {
      dieWithHelp($command,
         "The command \"$command\" does not accept the option \"$opt\"");
   }
   if ($options{$opt}->{hasarg} and exists $options{$opt}->{check}) {
      if (not $options{$opt}->{check}($haveopts{$opt})) {
         dieWithHelp($command, $options{$opt}->{error});
      }
   }
}

###
### COMMANDS
###

sub help(;$) {
   my $subject = shift;
   if (not $subject) {
      usage() if (not @haveargs) || ($haveargs[0] eq 'help');
      $subject = $haveargs[0];
   }
   if (not exists $commands{$subject}) {
      dieWithUsage("The command '$subject' is unknown");
   }
   my @help = split(/\n\n/, $commands{$subject}->{help});
   @help = map { $_ =~ s/^\n+|\n+$//gs; $_ } @help;

   if ($havewrap) {
      @help = map { $_ =~ s/(?<!\n)\n(?!\n)/ /gs; $_ } @help;
   }

   printf("COMMAND: %s %s\n\n", $subject, $commands{$subject}->{usage});
   map { print STDOUT $wrap->($prepad, $pad, $_) . "\n\n" } @help;

   if (not exists $commands{$subject}->{options}) {
      return;
   }

   if (@{$commands{$subject}->{options}}) {
      printf("OPTIONS\n\n");
      for my $option (@{$commands{$subject}->{options}}) {
         my $hasarg = $options{$option}->{hasarg};
         printf("$pad$option%s\n", $hasarg ? ' <argument>' : '');
         @help = split(/\n\n/, $options{$option}->{help});
         @help = map { $_ =~ s/^\n+|\n+$//gs; $_ } @help;
         @help = map { $_ =~ s/(?<!\n)\n(?!\n)/ /gs; $_ } @help if $havewrap;
         map { print STDOUT $wrap->($prepad, $prepad, $_) . "\n\n" } @help;
      }
   }
}

# a copy is just an unpacked export
sub copy() {
   export();
}

sub export() {
   my $cmdlinepath = $haveopts{"--confpath"};
   $confpath = $cmdlinepath if defined $cmdlinepath;
   while (substr($confpath, -1) eq '/') {
      $confpath = substr($confpath, 0, -1);
   }

   # FIXME: we can import and list from target tarballs ... so why not export?
   # The reason is the use of the 'tar' command in this function, a better
   # solution will be to create the tar archive in code a-la TarReader.pm, then
   # we can just shunt data from tar to tar programmatically
   if (not -d $confpath) {
      error("Configuration path '$confpath' is not a directory");
      exit(1);
   }


   my %exclusions;
   if (exists $haveopts{'--exclude'}) {
      for my $ex ( @{$haveopts{"--exclude"}} ) {
         my @parts = grep { $_ ne "" } split( '/', $ex );
         $ex = join( '/', @parts );
         $exclusions{$ex} = 1;
      }
   }
   my $description = $haveopts{"--description"};

   my $dest = $command eq "export" ? $haveopts{"--file"} : $haveopts{"--destdir"};

   if (not @haveargs) {
      push @haveargs, "";
   }

   my $err;
   my $version = Zeus::ZXTM::ConfManagement::getVersion($confpath, \$err);
   my $cmdlinever = $haveopts{"--version"};
   if (not $version and not $cmdlinever) {
      error(
         "Unable to get configuration version.  Either ensure that " .
         "the configuration path ($confpath) is valid or if working with " .
         "an orphaned configuration tree provide a version using the " .
         "--version option.");
      exit(1);
   } elsif ($version and $cmdlinever) {
      warning(
         "Version $cmdlinever was specified, yet the source configuration " .
         "is located in a Stingray software install with version $version. If " .
         "the version is incorrect this may result in configuration " .
         "corruption at import time. The configuration export will " .
         "continue using the supplied version.");
   }
   $version = $cmdlinever if $cmdlinever;
   trace(1, "Configuration version: $version");

   local *OUT = *STDOUT;
   my ($ddir, $dfile);
   if ($command eq "export" and defined $dest) {
      $dest = deTilde($dest);
      if ($dest =~ m/^(.*)\/([^\/]*)$/) {
         ($ddir, $dfile) = ($1, $2);
      } else {
         ($ddir, $dfile) = (getcwd(), $dest);
      }
      if (not open(*OUT, '>', $dest)) {
         error("Unable to open output file: $dest: $!");
         exit(1);
      }
   } elsif (not defined $dest) {
      $dest = getcwd();
   }
   if ($command eq "copy") {
      if (not -e "$dest") {
         error("Destination directory ($dest) does not exist");
         exit(1);
      }
      if (not -d "$dest") {
         error("Destination directory ($dest) exists but is not a directory");
         exit(1);
      }
      if (not -w "$dest") {
         error("Destination directory ($dest) exists but is not writable");
         exit(1);
      }
      if (-e "$dest/conf") {
         error("Destination directory ($dest) must not already contain a " .
               "'conf' sub-directory");
         exit(1);
      }
   }

   my ($confparent, $conf);
   if ($confpath =~ m/^(.*)\/([^\/]*)$/) {
      ($confparent, $conf) = ($1, $2);
   } else {
      ($confparent, $conf) = (getcwd(), $confpath);
   }

   if ($command eq 'export' and $verbosity > 1) {
      trace(1, "Source dir: $conf");
      trace(1, "Source parent: $confparent");
      trace(1, "Destination dir: " . ($ddir || "<none>"));
      trace(1, "Destination file: " . ($dfile || "<STDOUT>"));
   }

   # get list of files to include in the export
   my (@list, @errs);
   Zeus::ZXTM::ConfManagement::list($confpath, \@list, \@errs, @haveargs);
   # print errors for any files that caused problems
   foreach my $error (sort @errs) {
      error( $error );
   }

   if( @errs ) {
      exit( -1 );
   }

   my $dry_run = ( exists $haveopts{"--dryrun"} ) ? 1 : 0;

   # create and execute 'tar' command, capturing the tar file data in $tar
   my @tarcmd;
   my %dirs;
   my $empty = 1;
   my $excluded = 0;
   my $afm_confbackup = undef;
   for my $file (sort @list) {
      if ( exclusionMatch( \%exclusions, $file ) ) {
         $excluded = 1;
         next;
      } else {
         if( $dry_run ) {
            print( "$file\n" );
         } elsif( $file eq $Zeus::ZXTM::AFMUtils::afm_config_archive ) {
            # this file has a special meaning
            my( $afm_err, $afm_backupfile ) = HandleSAF_BackupCreation();
            if( $afm_err ) {
               warning( "Failed to create App Firewall configuration: $afm_err" );
               next;
            } elsif( defined( $afm_backupfile ) && -r $afm_backupfile ) {
               $afm_confbackup = "$confparent/$conf/$file";
               copy_file( $afm_backupfile, $afm_confbackup );
               if( ! -f $afm_confbackup ) {
                  warning( "Failed to copy temporary AppFirewall config file to $afm_confbackup" );
               }
               if( !unlink( $afm_backupfile ) ) {
                  warning( "Failed to delete temporary AppFirewall config file $afm_backupfile: $!" );
               }
            }
         }
         trace( 1, "Including: $conf/$file" );
         push( @tarcmd, "$conf/$file" );
         $empty = 0;
      }
   }
   for my $file (keys %exclusions) {
      warning("Excluded file name '$file' not in file list")
         if $exclusions{$file};
   }

   if( $empty ) {
      if ( $excluded ) {
         error( "All files were excluded from the export" );
      } else {
         error( "No files matched the source path(s) and filter specification" );
      }
      exit( 1 );
   }

   if( $dry_run ) {
      return;
   }

   unshift( @tarcmd, "-" );
   unshift( @tarcmd, "-chf" );
   unshift( @tarcmd, "tar" );
   my $cwd = getcwd();
   if( !chdir( $confparent ) ) {
      error( "Unable to change directory to: $confparent: $!" );
      exit( 1 );
   }

   my( $exit, $tar, $stderr ) = execute( \@tarcmd );
   if( defined( $afm_confbackup ) && -f $afm_confbackup &&
       !unlink( $afm_confbackup ) ) {
      warning( "Failed to delete AppFirewall config file $afm_confbackup: $!" );
   }
   chdir($cwd);

   if ($stderr) {
      warning('Non-fatal error output from tar command: ' . $stderr);
   }
   if ($exit != 0) {
      error('Non-zero exit code from tar: ' . $exit);
      exit($exit);
   }

   tarAppend(\$tar, "conf/VERSION_$version", "");
   if (defined $description) {
      tarAppend(\$tar, "conf/DESCRIPTION", $description);
   }
   tarAppend(\$tar, "conf/PARTIAL", "");
   tarAppend(\$tar, "conf/TIMESTAMP", "");
   if ($command eq 'export') {
      print OUT $tar;
      close(OUT); # may close STDOUT, but there should be no more STDOUT writes
   } else {
      if (not chdir($dest)) {
         error("Unable to change directory to: $dest: $!");
         exit(1);
      }
      my( $exit, undef, $stderr ) = execute( ['tar', '-xpf', '-'], $tar );
      if ($stderr) {
         warning('Error output from tar: ' . $stderr);
      }
      if ($exit != 0) {
         error('Non-zero exit code from tar: ' . $exit);
         exit($exit);
      }
   }
}

# replicate() is required by import --replicate
sub replicate();
# TODO: the import (also diff) code needs some refactoring and should be
#       moved into ConfManagement so it can be used by the UI in the future.
sub import() {
   my $filter;
   my ($source, $target) = @haveargs;
   $target = $confpath if not $target;
   if (not defined $source) {
      error("The '$command' command requires a source argument.");
      exit(1);
   }
   ($source, $target) = (deTilde($source), deTilde($target));
   trace(1, "Source is: $source");
   trace(1, "Target is: $target");

   # verify source
   my $sversion;
   if (exists $haveopts{'--sourceversion'}) {
      $sversion = $haveopts{'--sourceversion'};
   } elsif (-e $source) {
      my $err;
      $sversion = Zeus::ZXTM::ConfManagement::getVersion($source, \$err);
      if (not $sversion) {
         error("$source: $err");
         exit(1);
      }
   } else {
      error( "Source '$source' must be an existing file or a directory." );
      exit(1);
   }
   trace(1, "Source version is: $sversion");

   # verify target
   if (not -d $target) {
      error("The target must be a Stingray configuration directory.");
      exit(1);
   }
   my $err;
   my $tversion = Zeus::ZXTM::ConfManagement::getVersion($target, \$err);
   if (not $tversion) {
      error("$target: $err");
      exit(1);
   }
   trace(1, "Target version is: $tversion");

   # TODO: it would be desirable to support importing lower version to higher,
   #       which would require use of the upgrade code...
   if ($tversion ne $sversion) {
      error("Source (" . $sversion . ") and target (" . $tversion . ") " .
            "versions are not the same");
      exit(1);
   }

   # work out what filter definition we're using
   my @filterlines;
   if (exists $haveopts{"--filter"}) {
      if (not open(FILTER, "<" . $haveopts{"--filter"})) {
         error("Failed to open specified filter file: "
               . $haveopts{"--filter"} . ": $!");
         exit(1);
      }
      @filterlines = <FILTER>;
      close(FILTER);
      trace(1, "Loading filter definition from '" . $haveopts{"--filter"} . "'");
   } elsif (not exists $haveopts{"--no-filter"}) {
      @filterlines = Zeus::ZXTM::ConfManagement::getDefaultFilter();
      trace(1, "Using default filter definition.");
   } else {
      trace(1, "No filter configuration loaded.");
   }
   # parse the filter
   if (@filterlines) {
      my @badlines;
      $filter = Zeus::ZXTM::ConfManagement::parseFilter(
         \@filterlines, \@badlines);
      if (@badlines) {
         error("Filter file '" . $haveopts{"--filter"}
                  . "' contains invalid lines:");
         foreach (@badlines) {
            chomp;
            print "      $_\n";
         }
         exit(1);
      }
      trace(1, "Filter contains " . scalar @{$filter}
         . (scalar @{$filter} > 1 ? " entries." : " entry."))
   } else {
      trace(1, "No filter entries loaded.");
   }
   # report details about the filter
   if ($verbosity > 2) {
      for my $f (@{$filter}) {
         trace(2, "FILTER: FILE RE: '" . $f->[0] . "' => KEY RE: "
            . (defined $f->[1] ? "'" . $f->[1] . "'" : "<whole-file>"));
      }
   }
   # add filters for metadata files
   push @{$filter}, [ "PARTIAL", undef ];
   push @{$filter}, [ "VERSION_.*", undef ];
   push @{$filter}, [ "TIMESTAMP", undef ];
   push @{$filter}, [ "DESCRIPTION", undef ];

   

   # obtain source file list
   my @include = ( "" );
   if (exists $haveopts{"--include"}) {
      @include = @{$haveopts{"--include"}};
   }
   my (@filelist, @errors);
   my $error = Zeus::ZXTM::ConfManagement::list(
      $source, \@filelist, \@errors, @include );
   if ($error) {
      error($error);
      exit(1);
   }
   for my $error (@errors) {
      error($error);
   }
   if( @errors ) {
      exit( 1 );
   }

   # if this is a dry run push the verbosity up
   $verbosity = 3 if exists $haveopts{"--dryrun"};

   # apply file-level filters
   my %selectedlist;
   map { $selectedlist{$_} = 1 } @filelist;

   for my $file (keys %selectedlist) {
      for my $f (@{$filter}) {
         if (not defined $f->[1] and $file =~ /^$f->[0](?:(?<=\/)|\/|$)/) {
            trace(2, "IGNORING SOURCE FILE $file: Matches filter: $f->[0]");
            delete $selectedlist{$file};
            last;
         }
      }
   }

   # Create Storage Managers
   my $sourcemgr = new Zeus::ZXTM::StorageManager( $source );
   my $targetmgr = new Zeus::ZXTM::StorageManager( $target ); 

   # The SSL certificates depend on the ssl/<type>_config file. We need to 
   # merge in config keys for SSL certs that will be kept from the target
   # config.
   for my $file ( keys( %selectedlist ) ) {
      if( $file =~ /^ssl\/([^\/]+)_config$/ ) {
         my $ssl_type = $1;
         if( $targetmgr->existsConfig( $file ) ) {
            my $tcfg = $targetmgr->getConfig( $file );
            my $scfg = $sourcemgr->getConfig( $file );
            
            my @merge_keys = $tcfg->listA( '[^!]+!' );
            foreach my $key ( @merge_keys ) {
               next if( $key !~ /^([^!]+)!/ );
               my $cert_name = $1;
               my $cert_path = "ssl/$ssl_type/$cert_name.public";

               if( ! $targetmgr->existsConfig( $cert_path ) &&
                   ! $sourcemgr->existsConfig( $cert_path ) )
               {
                  next;
               }

               if( ! $scfg->exists( $key ) ) {
                  trace( 3, "Auto-adding filter: $file -> $key" );
                  push( @$filter, [ $file, $key ] );
               }
            }
         }
      }
   }

   my $target_is_running_instance = ($target eq $confpath &&
                                     -r "$target/../internal/pid" &&
                                     pidRunning( "$target/../internal/pid" ) );

   my $afm_was_enabled = safe_check_afm_enabled( $targetmgr );

   trace( 4, "target is " . ($target_is_running_instance ? "": "not ")
          . "a running instance, application firewall is "
          . ($afm_was_enabled? "" : "not "). "enabled" );

   # now merge the source into the target

   my (@copy, @copyconf, @copy_not_conf, @commit, @afm_backup);
   for my $file (keys %selectedlist) {
      trace(1, "PROCESSING CONFIG FILE: $file");
      my @keyfilters;
      for my $f (@{$filter}) {
         if ($file =~ /^$f->[0]$/) {
            push @keyfilters, $f->[1];
         }
      }
      my $scfg = $sourcemgr->getSpecificConfig( $file );
      if (not $scfg) {
         # not a key-value-config ...

         # could be an ApplicationFirewallConfig backup...
         if( $file eq $Zeus::ZXTM::AFMUtils::afm_config_archive ) {
            trace(2, "TRY TO RESTORE APPFIREWALL CONFIG FILE $file.");
            @afm_backup = ( $file );
         } else {
            # otherwise, copy it
            trace(2, "COPY ENTIRE FILE $file: Not a Key-Value config file.");
            push @copy, $file;
            push @copy_not_conf, $file;
         }
         # for the time being this warning applies to both afm config and 'opaque' files:
         if (@keyfilters) {
            warning("Key filter specified for non-key-value file: $file");
         }
      } elsif (not $targetmgr->existsConfig( $file )) {
         # doesn't exist in the target, copy it
         trace(2, "COPY ENTIRE FILE $file: Does not exist in target.");
         push @copyconf, $scfg;
         push @copy, $file;
      } elsif (not @keyfilters) {
         # no filters for the config, copy it
         trace(2, "COPY ENTIRE FILE $file: No matching filters.");
         push @copyconf, $scfg;
         push @copy, $file;
      } else {
         # it's a key-value config, it exists in the target, and we have filters
         my $tcfg = $targetmgr->getSpecificConfig( $file );
         # delete original keys
         for my $key ($tcfg->listAll()) {
            my @locations = ('');
            if ($tcfg->isKeyLocationSpecific($key)) {
               @locations = $tcfg->getLocationsDefinedFor($key);
            }
            for my $loc (@locations) {
               my $lkey = locationKey($key, $loc);
               my $keep = 0;
               for my $f (@keyfilters) {
                  if ($lkey =~ /^$f$/) {
                     $keep = 1;
                     trace(2, "PRESERVE KEY FROM TARGET $file: $lkey");
                     last;
                  }
               }
               if (not $keep) {
                  trace(2, "DELETE KEY FROM TARGET $file: $lkey");
                  $tcfg->delete($lkey);
               }
            }
         }
         # copy in non-filtered keys
         for my $key ($scfg->listAll()) {
            my @locations = ('');
            if ($scfg->isKeyLocationSpecific($key)) {
               @locations = $scfg->getLocationsDefinedFor($key);
            }
            for my $loc (@locations) {
               my $lkey = locationKey($key, $loc);
               my $keep = 1;
               for my $f (@keyfilters) {
                  if ($lkey =~ /^$f$/) {
                     $keep = 0;
                     trace(2, "IGNORE KEY FROM SOURCE $file: $lkey ($f)");
                     last;
                  }
               }
               if ($keep) {
                  $tcfg->set($lkey, $scfg->get($lkey));
                  trace(2, "COPY KEY FROM SOURCE $file: $lkey => " . $scfg->get($lkey ));
               }
            }
         }
         push(@commit, $tcfg);
      }
   }

   # verify merged configs using ConfigDescriptions.pm validation logic
   if (not exists $haveopts{"--no-verify"}) {
      my $validatefail = 0;
      my $afmports = GetAfmPortHash();
      for my $cfg (@commit, @copyconf) {
         next unless $cfg->isa("Zeus::ZXTM::KeyInfo");
         trace( 4, "Processing cfg object '". $sourcemgr->getFilename($cfg) ."' from section $cfg->{_section}" );
         my (%keyerrs, %valerrs);
         for my $key ($cfg->list()) {
            # unfortunately perl validation often doesn't work
            # (i.e. file exists verification)
            my ( $type, $msg, @rest ) = $cfg->getValueValidation( $key );
            next if $type eq 'perl';
            trace( 5, "Validating key '$key'" );
            my $nk = scalar( keys( %keyerrs ) );
            my $nv = scalar( keys( %valerrs ) );
            $cfg->validateKey($key, $cfg->get($key), \%keyerrs, \%valerrs);
            if( scalar( keys( %keyerrs ) ) > $nk ) {
               trace( 1, "Validating key '$key' added key errors" );
            }
            if( scalar( keys( %valerrs ) ) > $nv ) {
               trace( 1, "Validating key '$key' added " . (scalar( keys( %valerrs ) ) - $nv) . " value errors" );
            }
         }
         if (%keyerrs) {
            $validatefail = 1;
            for my $key (sort keys %keyerrs) {
               my @ers = getErrors(\%keyerrs, $key, $cfg->get($key));
               my $val = $cfg->get($key);
               if( !defined( $val ) ) {
                  $val = "<default>";
               }
               error("Key errors for " . $sourcemgr->getFilename($cfg) .
                  ":$key=>$val: " . join(", ", @ers));
            }
         }
         if (%valerrs) {
            for my $key (sort keys %valerrs) {
               my $errs = join(", ", getErrors(\%valerrs, $key, $cfg->get($key)));

               # Setting afm_enabled comes with a check whether all the
               # required ports are available. If afm is currently running,
               # they will be busy, of course.  Therefore, we have to
               # intercept that error here. Note: If this error is about
               # one of the afm ports, and the 'problem' is that the port
               # is in use, we just ignore the error.  The code below is left
               # as is to make it clear why
               if( exists( $afmports->{$key} ) &&
                   $errs =~ /Port \d+ is already in use/ ) {
                  if( !$target_is_running_instance ) {
                     # if we're not importing into a live deployment, 
                     # there is no need for this check (nor is it possible
                     # to check the ports in any meaningful way).
                     next;
                  } elsif( safe_check_afm_enabled( $targetmgr ) ) {
                     # if afm is currently enabled in the target those ports
                     # *should* be in use - by the afm processes
                     next;
                  } else {
                     # if it's not enabled, we don't care whether those ports
                     # are busy
                     next;
                  }
               }
               # workaround for read-only guard in AptimizeConfig and EventTypeConfig
               next if (( $cfg->isa("Zeus::ZXTM::AptimizeConfig") ||
                          $cfg->isa("Zeus::ZXTM::EventTypeConfig")) &&
                          $errs =~ m/built-in.*cannot be altered/ );
               my $val = $cfg->get($key);
               if( !defined( $val ) ) {
                  $val = $cfg->getDefault( $key );
                  if( !defined( $val ) ) {
                     $val = "<undefined>";
                  }
               }
               error("Value errors for " . $sourcemgr->getFilename($cfg) .
                     ":$key=>$val: " . $errs );
               $validatefail = 1;
            }
         }
      }
      if ($validatefail) {
         error("Exiting due to validation failures.");
         exit(1);
      }
   }

   # handle the case that the command being run is 'diff'
   if ($command eq "diff") {
      for my $cfg (@copyconf, @commit, @copy_not_conf, @afm_backup) {

         # Non key value config
         if( ! ref( $cfg ) ) {
            my $filename = $cfg;

            if( $filename eq $Zeus::ZXTM::AFMUtils::afm_config_archive ) {
               print( "=== $filename => ",
                   ($target_is_running_instance? 'restore' : 'copy'),
                   " <= $filename\n" );
               next;
            } elsif( ! $targetmgr->existsConfig( $filename ) ) {
               print "=== $filename => copy\n";
               next;
            }
            
            # Check file size difference
            my $old_size = $targetmgr->getFileSize( $filename );
            my $new_size = $sourcemgr->getFileSize( $filename );
            trace( 2, "File $filename size: [ $old_size vs $new_size ]" );
            
            if( $new_size != $old_size ) {
               print "=== $filename => replace <= $filename\n";
               next;
            }

            # Calculate MD5s                     
            my $old_md5 = $targetmgr->md5File( $filename );
            if( ! $old_md5 ) {
               warning( "Could not determine MD5 for source file '$filename'" );
            }

            my $new_md5 = $sourcemgr->md5File( $filename );
            if( ! $new_md5 ) {
               warning( "Could not determine MD5 for target file '$filename'" );
            }

            trace( 2, "File $filename md5: [ $old_md5 vs $new_md5 ]" );
            
            if( !$old_md5 || !$new_md5 ) {
               print "=== $filename => ??? <= $filename\n";
            } elsif( $old_md5 ne $new_md5 ) {
               print "=== $filename => replace <= $filename\n";
            } else {
               print "=== $filename => identical <= $filename\n";
            }
            next;
         }

         # Key value config
         my $filename = $targetmgr->getFilename( $cfg );
         my $tcfg = $targetmgr->getSpecificConfig( $filename );
         print "=== $filename";
         if ($tcfg) {
            my $diff = $tcfg->diff($cfg);
            if (%{$diff}) {
               print " => merge <= $filename\n";
            } else {
               print " => identical <= $filename\n";
            }
            for my $key (sort keys %{$diff}) {
               if ($diff->{$key}->[0] eq '%') {
                  print "- $key\t" . $diff->{$key}->[1] . "\n";
                  print "+ $key\t" . $diff->{$key}->[2] . "\n";
               } else {
                  print $diff->{$key}->[0] . " $key\t" . $diff->{$key}->[1] . "\n";
               }
            }
         } else {
            print " => copy\n";
         }
      }
   }

   # don't commit any changes if this is a "dry run" of a diff
   return if exists $haveopts{"--dryrun"} or $command eq "diff";

   # write the changes to the target
   for my $file (@copy, $target_is_running_instance ? () : @afm_backup ) {
      trace(1, "COPYING: $source:$file -> $target:$file");
      my ($content, $err) = $sourcemgr->_readFile($file);
      if ($err) {
         warning("Error reading source file $file: $err");
      } else {
         my @bits = split('/', $file);
         pop @bits;
         my $path = "";
         for my $bit (@bits) {
            if (not $targetmgr->existsFolder($path . $bit)) {
               $targetmgr->makeFolder($path, $bit);
            }
            $path .= "$bit/";
         }
         $err = $targetmgr->_putFile($file, $content);
         if ($err) {
            warning("Error writing target file $file: $err");
         } else {
            my $mode;
            ($mode, $err) = $sourcemgr->_readFileMode($file);
            if ($err) {
               warning("Error reading mode of source file $file: $err");
            } else {
               $err = $targetmgr->_setFileMode($file, $mode);
               if ($err) {
                  warning("Error setting mode of target file $file: $err");
               }
            }
         }
      }
   }
   for my $cfg (@commit) {
      trace(1, "COMMITING: $target:" . $cfg->getFilename());
      $cfg->putToStorage();
   }
   if (not exists $haveopts{'--no-replicate'} and
         ($target eq $confpath or exists $haveopts{'--replicate'})) {
      $target =~ s/zxtm\/conf$//; # must be 'zxtm/conf' in a running install
      trace(1, "REPLICATING CLUSTER CONFIG FOR ZEUSHOME=$target");
      unshift @haveargs, $target;
      replicate();
   }
   if( $target_is_running_instance && scalar( @afm_backup ) ) {
      if( !$afm_was_enabled && safe_check_afm_enabled( $targetmgr ) ) {
         # if afm was disabled before applying this partial backup,
         # but is enabled now, we have to give the afm processes
         # some time to get up and running
         trace( 3, "Wait for application firewall running..." );
         my $afm_running = WaitForAFMRunning( storage => $targetmgr );
         trace( 3, $afm_running ? "... now running" : "... failed" );
      }
      trace( 1, "Restore ApplicationFirewallConfig from source" );
      my $afm_rest_state = getAFMRESTStateMessage( $targetmgr );
      if( $afm_rest_state->[0] eq 'OK' ) {
         # ok, the fw config is contained in the config as a file,
         # but the config can be a directory or based off a tar archive.
         # make sure the backup_tool can read the file from a location on disk
         my $backupfile = "/tmp/afm_backup.$$.zip";
         my $afm_config_zip = $afm_backup[0];
         if( $sourcemgr->copyFileTo( "$afm_config_zip", $backupfile ) ) {
            my $msg = HandleSAF_BackupRestore( $backupfile );
            if( "" eq $msg ) {
               trace( 1, "Successfully restored $afm_config_zip" );
            } else {
               warning( "$afm_config_zip could not be restored: $msg" );
            }
            if( !unlink( $backupfile ) && $! ne 'No such file or directory' ) {
               warning( "Failed to delete temporary AppFirewall config archive $backupfile: $!" );
            }
         } else {
            warning( "Failed to extract file '$afm_config_zip' from source config" );
         }
      } else {
         warning( "Unable to restore AppFirewall config: $afm_rest_state->[1]" );
      }
   }
}

sub diff() {
   # requires the import logic up to the point where the calculated final
   # config can be diffed against the initial target config
   import();
}

sub list() {
   my $cmdlinepath = $haveopts{"--confpath"};
   $confpath = $cmdlinepath if defined $cmdlinepath;
   while (substr($confpath, -1) eq '/') {
      $confpath = substr($confpath, 0, -1);
   }
   if (not @haveargs) {
      push @haveargs, "";
   }

   if (not exists $haveopts{"--assumeversion"}) {
      my $errstr;
      my $version = Zeus::ZXTM::ConfManagement::getVersion($confpath, \$errstr);
      if (not $version) {
         error($errstr);
         exit(1);
      }
   }

   my (@files, @errors);
   Zeus::ZXTM::ConfManagement::list( $confpath, \@files, \@errors, @haveargs );
   for (@files) {
      print "$_\n";
   }
   for (@errors) {
      warning($_);
   }
}

sub version() {
   my $cmdlinepath = $haveopts{"--confpath"};
   $confpath = $cmdlinepath if defined $cmdlinepath;
   while (substr($confpath, -1) eq '/') {
      $confpath = substr($confpath, 0, -1);
   }
   if (@haveargs) {
      error("Unexpected command line: " . join(" ", @haveargs));
      exit(1);
   }
   my $err;
   my $version = Zeus::ZXTM::ConfManagement::getVersion($confpath, \$err);
   if (not $version) {
      error($err);
      exit(1);
   }
   print STDOUT "$version\n";
}

sub replicate() {
   my $zh = $ENV{"ZEUSHOME"};
   if (@haveargs) {
      $zh = shift @haveargs;
   }
   if (not defined $zh) {
      error("No ZEUSHOME defined");
      exit(1);
   } elsif (not -d $zh) {
      error("ZEUSHOME value '$zh' is not a directory");
      exit(1);
   }
   trace(1, "Replicating configuration of software installed at: $zh");
   $ENV{"ZEUSHOME"} = $zh;

   # Replicate the configuration
   my( $exitcode, $stdout, $stderr ) =
       Zeus::Execute::execute(
         "$zh/zxtm/bin/replicate-config --timeout 30",
         undef, undef, undef, 30 );

   Zeus::ZXTM::StorageManager::updateZXTM();

   # If it all worked OK, no need to check errors
   return unless( $exitcode );

   # Report errors
   error("Failed to replicate configuration: $zh/zxtm/bin/replicate-config" .
         " exited with status $exitcode, and error output:");
   print STDERR $stderr;
   exit(1);
}

sub getdefaultfilter() {
   my @filterlines = Zeus::ZXTM::ConfManagement::getDefaultFilter();
   print join("\n", @filterlines) . "\n";
}

sub info() {
   my $confpath = shift @haveargs;
   if (not defined $confpath or $confpath eq "") {
      error("A CONFPATH argument must be specified");
      exit(1);
   }
   my $errstr;
   my $version = Zeus::ZXTM::ConfManagement::getVersion($confpath, \$errstr);
   if (not $version) {
      error($errstr);
      exit(1);
   }
   print "Version: $version\n";
   my $desc = Zeus::ZXTM::ConfManagement::getDescription($confpath, \$errstr);
   if ($errstr) {
      error($errstr);
   } else {
      print "Description: " . ($desc ? $desc : "<none>") . "\n";
   }
   $errstr = undef;
   my $ts = Zeus::ZXTM::ConfManagement::getTimestamp($confpath, \$errstr);
   if ($errstr) {
      error($errstr);
   } else {
      print "Timestamp: " .
         ($ts ? strftime('%F %T UTC', gmtime($ts)) : "<none>") . "\n";
   }
}

eval "$command()";
die $@ if $@;

## internal helper functions

sub safe_check_afm_enabled($)
{
   my( $targetmgr ) = @_;
   return $targetmgr->existsConfig( 'settings.cfg' ) &&
       AFMEnabledInConfig( $targetmgr );
}
