#!/usr/bin/perl
#
# Library for use with slbackup (Skolelinux Backup)
#
# Content:
#  - deal with configuration files
#  - deal with log files
#
# $Id: SLBackup.pm,v 1.6 2007-12-22 19:48:18 finnarne-guest Exp $
#
# Most of the code in this module is copied from the
# LRRD project (http://www.linpro.no/project/lrrd/)
#
# Thanks to Linpro AS for well written perl code!
#

package SLBackup;

use POSIX qw(strftime);
use Exporter;
@ISA = ('Exporter');
@EXPORT = ('run_scripts',
	   'slbackup_overwrite',
	   'slbackup_readconfig',
	   'slbackup_writeconfig',
	   'slbackup_config' );

use strict;
use Config::General;

my $config = undef;
my $configfile = '/etc/slbackup/slbackup.conf';
my $DEBUG = 0;


sub slbackup_readconfig {
    my ($conf, $missingok) = @_;
    $conf ||= $configfile;
    
    if (! -r $conf and ! $missingok) {
	print "slbackup_readconfig: cannot open '$conf'\n";
	return undef;
    }

    my $conffile = new Config::General(-ConfigFile => $conf,
                                       -CComments => 0);
    my $config = { $conffile->getall };
    return ($config);
}


sub slbackup_writeconfig {
    my ($datafilename, $data) = @_;
    
    my $datafile = new Config::General();
    $datafile->save_file($datafilename, $data);
}


# subroutine that runs scripts in a directory which is executable
# returns:
#  1: successfully executed all scripts in directory
#  -1: failed reading $dir
#  -2: one or more of the script failed while executing
sub run_scripts {
    my ($dir, $logfile, $debug) = @_;

    open (LOG, ">>$logfile") or die ("Unable to open $logfile\n");
    logger ("Start running executables in $dir.");

    # check that $dir is a directory
    if ( ! -d $dir || ! -r $dir ) {
	logger ("Failed reading files in script-directory $dir");
	return -1;
    }

    # find and execute all executables in $dir
    my $subretval = 1;
    my @scripts = `find $dir/ -type f; find $dir/ -type l`;
    my $script;
    
    foreach $script (sort @scripts) {
	# strip newline
	$script =~ tr/\n//d;
	# is $script executable?
	if ( -x $script ) {
	    my $output = `$script 2>&1`;
	    my $retval = $?;
	    if ($debug) {
		logger ("Debug-output from $script:\n $output\n" .
			"Debug-output from $script ended.");
	    }

	    if ( $retval eq 0) {
		logger ("Successfully run $script: \n$output");
	    } elsif ( $retval ne 0 ) {
		$subretval = -2;
		logger ("Unsuccessfully run $script:\n$output");
	    } else {
		logger ("Something strange happened to $script:\n$output");
	    }
	}
    }

    logger ("Finished running executables in $dir.");
    close (LOG);
    return $subretval;
}


sub logger {
    my ($comment) = @_;
    my $now = strftime "%b %d %H:%M:%S", localtime;
    printflush LOG ("$now - $comment\n");
}


1;

__END__
