#! /usr/bin/perl -w
#----------------------------------------------------------------------
# copyright (C) 2003-2007 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
# 
#----------------------------------------------------------------------

use strict;
use File::Find;
use File::Copy;

sub setup_logfile_symlink;

my $event = shift or die "Event name is required\n";

my $logfile_dir = "/etc/e-smith/events/$event/logfiles2timestamp";
if (-d $logfile_dir)
{
    # Prepare log rotation if required
    chdir $logfile_dir or die "Could not chdir to $logfile_dir: $!\n";;
    find({
	    no_chdir => 1,
	    follow => 0,
	    wanted => \&setup_logfile_symlink,
	    },
	    '.'
	);
}

exit 0;

sub setup_logfile_symlink
{
    return unless -f $_;
    s/^\.//;
    my $filename = $_;

    # Set up filenames to be used by syslog. We first set up symlinks
    # with known names, then use the value of the symlink when we
    # expand the configuration files
    my $time = time();

    if (-f "${filename}" and ! -l "${filename}")
    {
	my ($sec,$min,$hour,$mday,$mon,$year) = localtime($time - 1);
	my $target = sprintf("%s.%04d%02d%02d%02d%02d%02d",
	    $filename, $year+1900, $mon+1, $mday, $hour, $min, $sec);
	move("${filename}", "${target}") or
	    die "Could not move ${filename} to " .
		"${target}";
    }
    my ($sec,$min,$hour,$mday,$mon,$year) = localtime($time);
    my $target = sprintf("%s.%04d%02d%02d%02d%02d%02d",
	$filename, $year+1900, $mon+1, $mday, $hour, $min, $sec);

    if (-l "${filename}")
    {
	unlink("${filename}") or
	    warn "Could not unlink ${filename}";
    }
    symlink("${target}", "${filename}") or
	warn "Could not symlink ${target} to ${filename}";
}
