#!/usr/bin/perl

# used by monitor_iot.worker

use strict;
use warnings;
use DateTime;
use DateTime::Event::Sunrise;
use File::Basename;

my $basename = basename $0;

#my ($lat0,$lon0)=(-37.82727086,145.07792685);
my ($lat0,$lon0)=(-37.72,144.965);

# generating DateTime objects from a DateTime::Event::Sunrise object
my $sun = DateTime::Event::Sunrise->new(longitude => $lon0,
                                        latitude  => $lat0);

my ($timer, $force) = (@ARGV);
my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
  localtime(time);

my $dt = DateTime->new( year   => 1900+$year,
                        month  => $mon+1,
                        day    => $mday,
                        time_zone => 'Australia/Melbourne');

#    my ($sunrise, $sunset) = ($sun->sunrise_datetime($dt)->hms, $sun->sunset_datetime ($dt)->hms);
my ($sunrise, $sunset) = ($sun->sunrise_datetime($dt)->epoch, $sun->sunset_datetime ($dt)->epoch);

my $now=time;
my $now_str=localtime($now);
#  if (defined $timer_pid) {
# kill any old timers:
#    my $kill_timer = $timer_pid;
#    $timer_pid=undef;
#    print "Killing old light timers: $kill_timer\n";
#    kill "TERM", $kill_timer;
#  }
if (($now > $sunset && $now < $sunrise + 86400) || # before midnight
    ($now > $sunset-86400 && $now < $sunrise)) {   # after midnight
  print "$basename: $now_str: Night time (Melbourne)\n";
  exit 0;
} else { # daylight, and were turning off anyway, so turn off straight away instead
  print "$basename: $now_str: Day time (Melbourne)\n";
  exit 1;
}
