#!/usr/bin/perl
#
#   Gargoyle Client Software.  Tools to read, analyze and manage Argus data.
#   Copyright (c) 2000-2024 QoSient, LLC
#   All Rights Reserved
#
#  THE ACCOMPANYING PROGRAM IS PROPRIETARY SOFTWARE OF QoSIENT, LLC,
#  AND CANNOT BE USED, DISTRIBUTED, COPIED OR MODIFIED WITHOUT
#  EXPRESS PERMISSION OF QoSIENT, LLC.
#
#  QOSIENT, LLC DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS
#  SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
#  AND FITNESS, IN NO EVENT SHALL QOSIENT, LLC BE LIABLE FOR ANY
#  SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
#  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
#  IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
#  ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
#  THIS SOFTWARE.
#
#   radns-nightly - DNS nightly scripts to manage dns databases.
#                   Need to generate dnsNames table (radnsdb).
#
#
# Complain about undeclared variables
use v5.6.0;
use strict;
use warnings;

use POSIX;
use File::Which qw/ which where /;
use Time::Local;

$ENV{'PATH'} = "/bin:/usr/bin:/usr/sbin:/usr/local/bin";

# Parse the arguments if any
my @arglist = ();

my $radnsdb   = which 'radnsdb';
my $debug     = 0;
my $dryrun    = 0;
my $done      = 0;
my $time;

ARG: while (my $arg = shift(@ARGV)) {
    if (!$done) {
      for ($arg) {
         s/^-debug$//      && do { $debug++; next ARG; };
         s/^-dryrun$//     && do { $dryrun++; next ARG; };
         s/^-t$//          && do { $time = shift(@ARGV); next ARG; };
         s/^-time$//       && do { $time = shift(@ARGV); next ARG; };
      }
    } else {
      for ($arg) {
         s/\(/\\\(/        && do { ; };
         s/\)/\\\)/        && do { ; };
      }
   }
    $arglist[@arglist + 0] = $arg;
}

if ((not defined $time) || ($time eq "-1d") || ($time eq "Yesterday")) {
   $time = RaYesterdaysDate();
} else {
   if ($time eq "Today") {
      $time = RaTodaysDate();
   }
}

my $cmd = "$radnsdb -time $time -drop";
$cmd = $cmd." -debug" if $debug;
print "DEBUG: RaDbManageData: cmd: $cmd\n" if $debug;
if ($dryrun == 0) {
   system($cmd);
}
exit;

sub RaTodaysDate {
  my ($sec, $min, $hour, $day, $mon, $year) = localtime();
  my $date = sprintf( "%04d/%02d/%02d", $year+1900, $mon+1, $day);

  print "DEBUG: RaTodaysDate: $date\n" if $debug;
  return $date;
}

sub RaYesterdaysDate {
  my ($sec, $min, $hour, $day, $mon, $year) = localtime();
  my  $yesterday = timelocal(0,0,12,$day,$mon,$year) - 24*60*60;
  ($sec, $min, $hour, $day, $mon, $year) = localtime($yesterday);

  my $date = sprintf( "%04d/%02d/%02d", $year+1900, $mon+1, $day);
  print "DEBUG: RaYesterdaysDate: $date\n" if $debug;
  return $date;
}
