#!/usr/bin/perl

use strict;
use warnings qw(all);
use Time::localtime;
use Net::FTP;

our $config;
my $date;
my $config_file = '/etc/backup.conf';
my $zones;

#  Check config file
die "Can't open config file !" 
	unless (-r $config_file);

# Read config file
require $config_file;

# Compute current day (YYYYMMDD)
{
	my $buffer = localtime;
	$date = sprintf ("%04d%02d%02d", $buffer->year + 1900, $buffer->mon +1, $buffer->mday);
}

# Connect to FTP 
my $ftph;
$ftph = new Net::FTP($config->{'ftp'}->{'host'},
                     Port => $config->{'ftp'}->{'port'})
	or die "FTP: Can't connect $@";

$ftph->login ($config->{'ftp'}->{'user'}, $config->{'ftp'}->{'pass'})
	or die "FTP: Can't login $@";

$ftph->cwd($config->{'ftp'}->{'path'})
	or die "FTP: Can't change directory $@";


# Read list of zones
my $fh;

open ($fh, "< /etc/zones/index")
	or die "Can't open /etc/zones/index for reading !";

while (<$fh>) {
	# Skip comments and blank lines
	next if (/^#/);
	next if (/^$/);
	# skip global zone
	next if (/^global:/);

	chomp;

	my ($zone, undef, $path) = split (/:/);
	$zones->{$zone}->{'path'} = $path;
}
close ($fh);

open ($fh, "< /etc/mnttab")
	or die "Can't open /etc/mnttab for reading !";

# Device
while (<$fh>) {
	chomp;
	my @buffer = split (/\t/);
	foreach my $zone (keys %{$zones}) {
		($zones->{$zone}->{'device'} = $buffer[0]) =~ s/dsk/rdsk/
			if ($buffer[1] eq $zones->{$zone}->{'path'});
	}
}
close ($fh);

mkdir $config->{'misc'}->{'tmp'}
	unless (-d $config->{'misc'}->{'tmp'});

# Proceed dumps, and send it
foreach my $zone (keys %{$zones}) {
	my $filename = $config->{'misc'}->{'tmp'} . '/' . $zone . '-' . $date . '.dump';
	system('ufsdump', '0f', $filename, $zones->{$zone}->{'device'});
	if ($config->{'misc'}->{'gzip'}) {
		system('gzip', '-f', $filename);
		$filename .= '.gz';
	}
	$ftph->put($filename);
	unlink $filename;
}
