#! /usr/bin/perl -w
#----------------------------------------------------------------------
# copyright (C) 2002 Mitel Networks Corporation
# 
# 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
# 
# Technical support for this program is available from Mitel Networks 
# Please visit our web site www.mitel.com/sme/ for details.
#----------------------------------------------------------------------

use strict;
use esmith::ConfigDB;
use esmith::BackupHistoryDB;

$ENV{PATH} = "/sbin/e-smith:/sbin:/bin:/usr/bin";

my $conf = esmith::ConfigDB->open || die("Could not open config db\n");
my $backup = $conf->get('backup');
my $status = $backup->prop('status') || 'disabled';
my $program = $backup->prop('Program') || 'flexbackup';
my $backupType = $backup->prop('BackupType') || 'tape';

unless ($status eq 'enabled')
{
    print "Backup is disabled\n";
    exit 0;
}

my $backups = esmith::BackupHistoryDB->open
    || die("Could not open backup history db\n");
my $now = time();
die "backup not allowed twice at the same date/time, delayed to next day\n" if $backups->get($now);
my $backup_rec = $backups->new_record($now, { type => 'backup_record' });
$backup_rec->set_prop('StartEpochTime', "$now");
$backup_rec->set_prop('BackupType', $backupType);

if ($status = system(qw(signal-event pre-backup), $backupType))
{
    exit bad_exit($backup_rec, "pre-backup", $status);
}

if ($status = system("/etc/e-smith/events/actions/tape-backup-$program"))
{
    exit bad_exit($backup_rec, "backup", $status);
}

if ($status = system(qw(signal-event post-backup), $backupType))
{
    exit bad_exit($backup_rec, "post-backup", $status);
}

$now = time();
$backup_rec->set_prop('EndEpochTime', "$now");
$backup_rec->set_prop('Result', "$status");
exit 0;

sub bad_exit
{
    my ($backup_rec, $phase, $status) = @_;
    my $now = time();

    warn("Backup terminated: $phase failed - status: $status\n");
    $backup_rec->set_prop('EndEpochTime', "$now");
    $backup_rec->set_prop('Result', "$phase:$status");
    return $status / 256;
}
