#!/usr/pkg/bin/perl -w
# -*-perl-*-

#  Copyright 2008 Google Inc.
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.

use strict;

use Date::Calc qw(Delta_DHMS);
use Getopt::Long;

my( $dfs, $start, $end, $help, $show_version );
$dfs = 'YYYY-MM-DD';
Getopt::Long::Configure( "no_ignore_case" );
&GetOptions("help" => \$help,
            "start=s" => \$start,
            "end=s" => \$end,
            "format=s" => \$dfs,
            "Version" => \$show_version,
           );

if ($show_version) {
  crush_version();
  exit(0);
}

if (! defined($start)) {
  $start = shift(@ARGV);
}
if (! defined($end)) {
  $end = shift(@ARGV);
}

if ($help || !(defined($start) && defined($end))) {
  usage();
  exit(1);
}

my @dhms = Delta_DHMS(date_parse($dfs, $start), date_parse($dfs, $end));
print abs($dhms[0]) + 1, qq(\n);
exit(0);

sub usage {
  print STDERR <<ENDUSAGE;

calculates the number of days in a range

usage: $0 [-s <date>] [-e <date>] [-f <format>] [start] [end]

  -h, --help    print this message and exit.
  -s, --start <date>  start date of range
  -e, --end <date>  end date of range
  -f, --format <format>  date format to use (default: YYYY-MM-DD)

ENDUSAGE
}


sub date_parse {
  my $fmt = shift;
  my $datestr = shift;

  return undef unless ($fmt && $datestr);

  my $YY  = index($fmt, 'YYYY');
  my $MM  = index($fmt, 'MM');
  my $DD  = index($fmt, 'DD');
  my $HH  = index($fmt, 'HH');
  my $MI  = index($fmt, 'MI');
  my $SS  = index($fmt, 'SS');

  my ($y, $m, $d, $h, $i, $s) = (0, 0, 0, 0, 0, 0);
  $y = substr($datestr, $YY, 4) if($YY != -1);
  $m = substr($datestr, $MM, 2) if($MM != -1);
  $d = substr($datestr, $DD, 2) if($DD != -1);
  $h = substr($datestr, $HH, 2) if($HH != -1);
  $i = substr($datestr, $MI, 2) if($MI != -1);
  $s = substr($datestr, $SS, 2) if($SS != -1);

  return ($y, $m, $d, $h, $i, $s);
}

sub date_format {
  my $fmt = shift;
  my ($y, $m, $d, $h, $i, $s) = @_;

  return undef unless ($fmt);

  $y = sprintf("%.4d", $y) if defined($y);
  $m = sprintf("%.2d", $m) if defined($m);
  $d = sprintf("%.2d", $d) if defined($d);
  $h = sprintf("%.2d", $h) if defined($h);
  $i = sprintf("%.2d", $i) if defined($i);
  $s = sprintf("%.2d", $s) if defined($s);

  $fmt =~ s/YYYY/$y/g;
  $fmt =~ s/MM/$m/g;
  $fmt =~ s/DD/$d/g;
  $fmt =~ s/HH/$h/g;
  $fmt =~ s/MI/$i/g;
  $fmt =~ s/SS/$s/g;

  return $fmt;
}

1;


sub crush_version {
  print STDERR "CRUSH tools release 2013-04 compiled at 2025-10-03-13:58:39\n";
}

1;
