#!/usr/bin/perl
#
#
$|=1;

$wait_time  = $ARGV[0] || 1;    # wait cycle [minutes]  default 1 [minuyes]
$wait_count = $ARGV[1] || 5;    # wait count            default 5 times

$my_proc = $0;   # ʬprocess̾

# ʬȤʣ¸ߤƤ뤫ǧ2İʾξϤ˽λ롣
#
 @lists = `/bin/ps -ax`;
 $process_myself = 0;
 for ($i = 0; $i < @lists; $i++){
     $list = $lists[$i];
     $list =~ s/[\r\n]//;
     $list =~ s/^ +//;
     $list =~ s/ +/ /g;
     ($pid,$tty,$stat,$time,$proc,@arg) = split(/ +/,$list);
     $process_myself++ if($list =~ /$my_proc/);
  }
# print "[",$my_proc,"] is ",$process_myself," exist\n";
# print "wait_time = $wait_time  wait_count = $wait_count\n";
# print "PID = $$\n";
 exit if($process_myself >=2);  # 2İʾϤ˽λ

# PIDֹ /var/run/agent_retry.pid˽񤭹
#
 open (PID,">/var/run/agent_retry.pid");
 print PID "$$\n";
 close (PID);
 
 $wait_time = $wait_time * 60;  # wait seconds
 
 $count = 0;
 while(1){
#    print "count=$count\n";
    sleep $wait_time;    # ֥꡼
# upsagent ץ̵ͭå
#
    @lists=""; $list="";
    $upsagent_proc = 0;
    @lists = `/bin/ps -ax`;
    for ($i = 0; $i < @lists; $i++){
        $list = $lists[$i];
        $list =~ s/[\r\n]//;
        $list =~ s/^ +//;
        $list =~ s/ +/ /g;
        ($pid,$tty,$stat,$time,$proc,@arg) = split(/ +/,$list);
        $upsagent_proc++ if($list =~ /upsagent/i);
    }

# upsagent lock file̵ͭå
#
    @locks=""; $lock="";
    $upsagent_lock = 0;
    @locks = `ls -1 /var/lock/subsys/*`;
    for ($i = 0; $i < @locks; $i++){
       $upsagent_lock++ if($locks[$i] =~ /upsagent/i);
    }
    
    # upsagent ץʤlock file¸ ǵưץȤ¹Ԥ
    #
    if($upsagent_proc == 0 and $upsagent_lock != 0){
       $retry = `/etc/rc.d/init.d/upsagent start >/dev/null 2>&1`;
    }
    # upsagent ץ or lock file¸ߤʤ ǽλ
    #
    if($upsagent_proc != 0 or $upsagent_lock == 0){
        system("rm -f /var/run/agent_retry.pid");
        exit;  # λ
    }
    sleep 5;
    $count++;
    if($count >=$wait_count){  # ꥫȲ򷫤֤
        system("rm -f /var/run/agent_retry.pid");
        exit;  # λ
    }
 }

exit;
