#!/usr/bin/perl
use strict;
use warnings;
use Getopt::Std qw{getopts};
use DateTime;
use DateTime::Event::Sunrise;
use Geo::Local::Server;

my $opt      = {};
getopts("f:m:s:", $opt);

my $syntax   = "sunset_time [-s '%H:%M'] [-f FILE] [-m +/-minutes]";
my $file     = $opt->{"f"};
my $offset   = $opt->{"m"} || 0;
my $strftime = $opt->{"s"} || '%H:%M';

die("$syntax\n") unless $offset =~ m/^[+-]?\d+$/;
my $now      = DateTime->now;
my $gls      = Geo::Local::Server->new(configfile=>$file);
my $lat      = $gls->lat;
my $lon      = $gls->lon;
my $sunset   = DateTime::Event::Sunrise
                 ->sunset(longitude=>$lon, latitude=>$lat)
                   ->next($now)
                     ->add(minutes=>$offset)
                       ->set_time_zone("local");

print $sunset->strftime($strftime). "\n";

__END__

=head1 NAME

sunset_time - Prints the time of the next sunset

=head1 SYNOPSIS

  sunset_time
  sunset_time [-f FILE] [-m +/-minutes]
  echo "task" | at `sunset_time`

=head1 OPTIONS

=head2 -f FILE - default /etc/local.coordinates

Specify alternate configuration file

=head2 -m Output offset in minutes

Specify a certain offset before or after the sunset

=head2 -s strftime

Specify a strftime format default: '%H:%M'

=head1 DESCRIPTION

Uses the system coordinates as configured from the perl package Geo::Local::Server and with the perl package DateTime::Event::Sunrise to calculate the next sunset.

=cut

