# -*-perl-*-

# $id$

# $Log: MorningReboot.plm,v $
# Revision 1.3  2004/01/13 16:48:31  thomas
# catch-up 1/13/04
#
# Revision 1.2  2003/12/15 16:28:35  thomas
# check-in for 0.1.1
#
# Revision 1.1.1.1  2003/12/02 14:47:35  thomas
# Initial version before export to 0.1.1
#


use strict;
use Data::Dumper;
use Schedule::At;
use Time::Local;
use FileHandle;

package What::Trigger::MorningReboot;
use base qw(What::Trigger);

our $done=0;

sub MorningReboot {
  my $trigger = shift;
  my $node = shift;  # The config object
  my $section = shift;
  my $what = shift;
  my $params = shift;

  $done++ and return;

  # This is too complicated...just use the local 'at' command
  # Figure out when the next 7am will be
  # my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
  # my $seconds = Time::Local::timelocal (0,0,7,$mday,$mon,$year);
  # $hour>=7 and $seconds += (3600*24);
  # ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($seconds);
  # my $thetime = sprintf ("%04d%02d%02d%02d%02d", $year+1900, $mon+1, $mday, $hour, $min);
  #$node->debug (2, "Scheduling /s/lab/bin/morning-reboot for $thetime\n");
  # Schedule::At::add(TIME => $thetime, COMMAND => '/s/lab/bin/morning-reboot');

  my $when = '7am';
  my $w1 = $section->find_node_attr ($section, '/Triggers/MorningReboot/when', 0);
  defined ($w1) and $when = $w1;
  exists ($params->{when}) and $when = $params->{when};

  my $at;
  foreach ('/bin/at', '/usr/bin/at') {
    if (-x $_) {
      $at = $_;
      last;
    }
  }

  my $command = '/s/lab/bin/morning-reboot';
  my $c1 = $section->find_node_attr ($section, '/Triggers/MorningReboot/command', 0);
  defined ($c1) and $command = $c1;
  exists ($params->{command}) and $when = $params->{command};

  $section->debug (2, "echo $command | $at $when\n");
  my $fh = new FileHandle "|$at $when";
  if (!defined $fh) {
    $section->err ("Failed to start $at $when\n");
    return 0;
  }
  print $fh $command;
  undef $fh;

  return 1;
}

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

=head1 NAME

What::Trigger::MorningReboot -- Schedule a reboot for the next
morning

=head1 DESCRIPTION

Create an at job to run /s/lab/bin/morning-reboot at 7:00 am.

The trigger contains a flag to keep multiple at jobs from being
scheduled in a single run of the configurator.

The time for the reboot can be modified in two ways.  If a B<when>
attribute is passed as part of the params structure when the node is
triggered, that time will be used.  If it is not, a B<when> attribute
of the B</Triggers/MorningReboot> node will be checked.  If neither of
those exist, the time '7am' will be used.

=head1 PARAMS

No params are required for this trigger.

The optional B<when> parameter can specify a time to pass to the B<at>
command.

The optional B<command> parameter can specify a command to run.

=cut

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

1;
