use strict;
use vars qw($VERSION $LOG
	%what_todo %need_network $todo $sysconfdir $loader %initval %pnest);

;# modules
use Fan::Loader;
use Fan::Cool;
use Fan;

;#
BEGIN {
	;# For non-blocking stdout.
	$| = 1;

	$LOG = 5;

	# Data and time string.
	my $t = time;
	my $s = str4date($t).' '.str4time($t);

	# Show start up message.
	warn("$s FTPMIRROR starting...\n") if $LOG > 5;
}

;#
END {
	# Data and time string.
	my $t = time;
	my $s = str4date($t).' '.str4time($t);

	;# Show terminate message.
	warn("$s FTPMIRROR terminated\n") if $LOG > 5;
}

;# initialization...
{
	use Config;

	# system configuration files
	$sysconfdir = $Config{prefix}.'/etc';
}

$what_todo{'full-mirror'} = 'run_full_mirror';
$what_todo{'step-mirror'} = 'run_step_mirror';
$what_todo{'scan-local'} = 'scan_local';
$what_todo{'scan-remote'} = 'scan_remote';
$what_todo{'mkdirinfo'} = 'mkdirinfo';
$what_todo{'synch-remote'} = 'step_synch';
$what_todo{'update-master'} = 'update_master';
$need_network{'full-mirror'} = 1;
$need_network{'step-mirror'} = 1;
$need_network{'scan-remote'} = 1;
$need_network{'synch-remote'} = 1;

;# check what shall we do
($todo) = $0 =~ m|([^/]+)$|;

;#
if (@ARGV > 0 && $ARGV[$[] =~ /^--(\S+)$/ && defined($what_todo{$1})) {
	$todo = $1;
	shift;
}

;#
if (!defined($what_todo{$todo})) {
	$todo = 'full-mirror';
}

;#
%initval = (
	'sysconfdir'			=> $sysconfdir,
	'load-config'			=> "ftpmirror.cf",
	'create-directories'		=> 1,
	'override-file-uid'		=> 0,
	'override-file-gid'		=> 0,
	'override-file-mode'		=> '0644',
	'override-directory-mode'	=> '0755',
	'default-file-uid'		=> 0,
	'default-file-gid'		=> 0,
	'default-file-mode'		=> '0644',
	'default-directory-mode'	=> '0755',
	'unlink'			=> 'yes',
	'backup-suffix'			=> '~',
);

;#
%pnest = (
	'archive'		=> 'PACKAGE::$_',
	'package'		=> 'PACKAGE::$_',
	'server'		=> 'SERVER::$_',
);

;#
$loader = Fan::Loader->new(
	loader_keys => \%Fan::pkeys,
	loader_nest => \%pnest,
);
ref($loader) && $loader->isa('Fan::Loader')
	or die("Can't create loader");

;# Initial default parameters.
$loader->merge_hash(\%initval, 'INIT')
	or die("Loader: Can't initialize values");

;# Parsing options.
$loader->parse_option($_, \@ARGV, 'OPTION')
	or die("Loader: Can't parse option: $_\n");

;# Set logging level first.
if (defined($_ = $loader->get_value('log-mask', 'INIT', 'OPTION'))) {
	plog_mask($_);
}

;# Get 'load-config' parameter
if (defined($_ = $loader->get_value('load-config', 'INIT', 'OPTION'))) {

	# get 'load-config' parameter
	my $dir = $loader->get_value('sysconfdir', 'INIT', 'OPTION');

# debug...
warn("load files = $_\n") if $LOG > 6;

	# load configuration files
	for my $file (split(/\s+/)) {
		next if $file eq '';
		$file = "$dir/$file" if ! -f $file && $dir ne '';
		warn("loading $file...\n") if $LOG > 5;
		$loader->parse_file($file, 'DEFAULT')
			or die ("Loader Can't parse $file.\n");
	}
}

#
$loader->dumpall;
exit;
