#!/usr/bin/perl -w
# 14 mars 2004
#
# PARTIE DAEMON
# 3 partie:
#     + Ecriture du pid dans /var/run/atscript.pid
#     + Changement des regles pour le signal USR1
#     + sleep indefini.
# les fichiers se nomment en fonction du temps en seconde a la quelle ils vont etre lances.
# 
##############################################################################

# INITIALISATION
use Proc::Daemon;
use strict;
Proc::Daemon::Init;

my ($current_time,$sec,$min,$hour,$mday,$mon,$year,$pid,@users,$user,@times);


$|= 1;
$SIG{'USR1'} = \&mise_a_jour;

#############################################################################

open(LOG,">>/home/tfe/truc/at/test_daemon/log") or die "log impossible";
select LOG;
print "\n\n".gmtime(time)."\n********************************************\nRuning $0\n";

if (-e "/var/run/atscript.pid")
{
open(PID,"/var/run/atscript.pid") or die "Unable to open /var/run/atscript.pid\n";
$pid = <PID>;
close PID;
}
if ($pid and kill 0 => $pid) { print LOG "Pid present et reactif\n";  die;}
else { 
    open(PID,">/var/run/atscript.pid") or die "PID impossible a ecrire";
    print PID $$;
    close PID;
    print "PAS DE PID (vivant) -> Nouveau pid ecrit\n"; 
}



&mise_a_jour;
#Lancement de la mise a jour au debut du script puis a chaque signal recu.

sub mise_a_jour
{
    $current_time = &make_time;    
    @users = &config() or die;
    
    foreach $user(@users){
        print "User: $user\n";
	print "ouverture de /home/$user/.atscript/\n";
        opendir(DIR,"/home/$user/.atscript/") or next;
        push (@times,"$_ $user")  foreach ( grep(! /^\./, readdir(DIR))); 
        close DIR;
    }	
    @times = sort @times;
    foreach (@times) { 
	($sec,$min) = split / /,$_; # user $min , #stop at $sec secondes.
	if ($sec < $current_time)
	    { unlink("/home/$min/.atscript/$sec") or print $!; 
	      print "/home/$min/.atscript/$sec is an obsolete file: deleted\n"; 
	    }
	    
	print "Sleep de $current_time a $sec:".($sec-$current_time)."\n"; $current_time = $sec; 
	}
}


#########################################################################
sub make_time
{
    ($sec,$min,$hour,$mday,$mon,$year) = localtime(time);
    if ($sec<10) { $sec = "0".$sec; }
    if ($min<10) { $min = "0".$min; }    
    if ($hour<10) { $hour = "0".$hour; }    
    if ($mday<10) { $mday = "0".$mday; }    
    if ($mon<10) { $mon = "0".$mon; }    
    $year = $year+1900;
    return $year.$mon.$mday.$hour.$min.$sec;
}

sub config {
    open(CONF,"/etc/atscript.conf") or die "Fatal: no config found /etc/atscript.conf\n";
    while(<CONF>)   {
        if (/^users:(.*)/) {
	@users = split(/ /,$1);
        }
    }
    close CONF;
    if (!@users) { die "Fatal: no config users set in /etc/atscript.conf\n"; }
    return @users;
}






print "Fin du lancement.\n";    
close LOG;

#while(1)
#{
#select(undef,undef,undef,1);
#}







