#!/usr/bin/perl -w
# debut 14 mars 2004
#
# PARTIE DAEMON
# 3 partie:
#     + Ecriture du pid fork dans /var/run/atscript.pid
#     + Ouverture d un pipe en lecture/ecriture
#     + sleep indefini pour ne pas quitter et garder un oeil sur le pipe.
# tfe@fallen-sun.com
# ##############################################################################

# INITIALISATION
use Fcntl;
require POSIX;
use strict;
use Proc::Daemon;
Proc::Daemon::Init;

my ($realpid,$forkpid,$logfile,$pipe,@users,$user,@times,$pid);
$|= 1;

my $path = "/home/tfe/truc/at/0.1/rund.pl";
$logfile = "/var/log/atscript";
$SIG{'CHLD'} = \&zombies;



sub log_send($)
{
    $_ = shift;
    open(LOG,">>$logfile");
    select LOG;
    print $_;
    close LOG;
}

sub kill_old
{

    log_send("KILL de l ancien pid.\n");
    if (open(PID,"/var/run/atscript.pid"))
    {
    $pid = <PID>;
    if (kill 0,$pid and $pid >0)
    {
    kill 'KILL',$pid or die $!;
    log_send("rund kill ($pid)\n");
    }
    close PID;
    }
    else {     log_send("pas  de PID trouve.\n"); }
}
    


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

log_send "\n\n".gmtime(time)."\n********************************************\nRuning $0\n";
 system("$path"); 
log_send("Fin mise a jour initiale!\n");
log_send("\n\n PID ATD: $$\n\n");
$realpid = $$;


$pipe = "/var/run/atscript";
if (-e $pipe) {    unlink $pipe;    }
POSIX::mkfifo($pipe,0666) or log_send "mknod failed $!\n";
chmod 0666, $pipe or log_send $!;
sysopen(FIFO,$pipe,O_RDWR) or log_send "LEcture failed\n";


#while(1)
# 
    while (<FIFO>)
    {
        if (/Update/) {     log_send "RECU: update !\n"; 
			    &kill_old; 
			    system("$path");
			    log_send("Fini...\n");
			    
	}
        elsif (/Show/) {   log_send "RECU: show !\n"; print FIFO "Recu !n\n\nRECU !!\n";}
	else { log_send  "Message inconnu recu !\n"; }
    }
#
log_send(" FIN DU PROG R A M M E  E E E E E E??????????????\n");

        





#########################################################################
sub zombies { 1 until (waitpid(-1 , 'WNOHANG') == -1); }
