#!/usr/bin/perl

# Copyright (C) 2008-2013 Zentyal S.L.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License, version 2, as
# published by the Free Software Foundation.
#
# 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

# This script is intended to make a configuration backup automatically daily

use strict;
use warnings;

use EBox;
use EBox::Config;
use EBox::Exceptions::Base;
use EBox::Exceptions::InvalidData;
use EBox::Gettext;
use EBox::RemoteServices::Backup;
use TryCatch::Lite;
use File::Slurp;
use Getopt::Long;
use Pod::Usage;

use constant LAST_BACKUP_TIMESTAMP_FILE => EBox::Config::conf() . 'remoteservices/last-backup-stamp';
use constant ATTEMPT_NUM => 2;

# Real make conf backup
sub makeConfBackup
{
    my $backupService = new EBox::RemoteServices::Backup();
    my $automatic     = 1;
    my $backupName    = 'automatic-backup-' . time();
    my $success       = 0;
    foreach my $attempt (1 .. ATTEMPT_NUM) {
        EBox::debug("Attempt $attempt to make the backup");
        try {
            $backupService->makeRemoteBackup($backupName,
                                             __('Automatic backup'),
                                             $automatic);
            $success = 1;
        } catch (EBox::Exceptions::InvalidData $e) {
            EBox::debug("Backup corrupted in some way...");
            $e->throw() if ($attempt == ATTEMPT_NUM);
        }
        last if ($success);
    }
}

# The following actions are done:
#
#    * Check if a new backup is needed
#    * Make the backup (retry ATTEMPT_NUM if corruption happens)
#    * Notify the backup resolution
#
sub checkMakeRetryConfBackup
{
    my $gl = EBox::Global->getInstance(1);
    my $rs = $gl->modInstance('remoteservices');
    if ( $rs->eBoxSubscribed() ) {
        my $lastBackupStamp = 0;
        if (-r LAST_BACKUP_TIMESTAMP_FILE) {
            $lastBackupStamp = File::Slurp::read_file(LAST_BACKUP_TIMESTAMP_FILE);
            chomp($lastBackupStamp);
        }
        # Make the conf backup if any change has been done to Zentyal
        if ($gl->lastModificationTime() > $lastBackupStamp) {
            try {
                makeConfBackup();
                # Save the timestamp for later use
                File::Slurp::write_file(LAST_BACKUP_TIMESTAMP_FILE, time());
                my $msg = __('Automatic configuration backup done');
                EBox::info($msg)
            } catch ($e) {
                my $msg = __x('Cannot make the automatic backup. {reason}',
                           reason => "$e");
                EBox::error($msg)
            }

        }
    }
}

# MAIN

# Get arguments
my ($usage) = (0);
my $correct = GetOptions(
    'usage|help' => \$usage,
   );

if ( $usage or (not $correct)) {
    pod2usage(1);
}

EBox::init();

checkMakeRetryConfBackup();

__END__

=head1 NAME

automatic-conf-backup - Utility to make a configuration backup daily

=head1 SYNOPSIS

automatic-conf-backup [--usage|help]

 Options:
    --usage|help  Print this help and exit

=cut

