#!/usr/bin/perl

## @file timeadj
# @brief This script adjusts system clock parameters to keep time accurate
# @details If there are no cli arguments provided then
#          user will be prompted to enter them
# @author Max Uvarov
# @date May 2008
# @version 1.00 - Initial version
# @version 1.01 - Two colons were removed before shared functions and variables.
# @note

=pod

=head1 NAME

B<timeadj> - Utility for system clock adjustment 

=head1 SYNOPSIS

B<timeadj> [B<-drift> I<< <-300.0 - 300.0 [sec]> >>] [B<--help> I<< <help> >>] [B<-show>
I<< <show> >>] [B<-reset> I<< <reset> >>]

=head1 DESCRIPTION

B<timeadj> - Allows tuning of system clock's frequency in case the clock gained or lost
time. The utility should be used on systems having no access to time reference source when
considerable time dfirt has been gained. The utility calculates and corrects system clock
frequency based on entered drift per day value.

The interactive mode will be launched if there are no CLI arguments provided.

=head1 OPTIONS

=over 4

=item B<-drift drift>

Specify the correction value. The drift must have the real number format (value is
between -300.0 and 300.0 [sec])

=item B<--help>

Show utility usage.

=item B<-show>

Show current system clock parameters

=item B<-reset>

Reset system clock parameters to default values. 
Tick: 10000  Freq: 0

=back

=head1 CAVEATS

B<timeadj> can be run only under nortel account, it requires the B<root> password to be run. 

=head1 SEE ALSO

B<timeadj>

=cut

use warnings;
use strict;

use lib "/opt/nortel/base/lib";

use Getopt::Long;
use common_variables;
use common_functions;
use baselog;
use base_timedate;
use CommonInstallUtils qw(header getYNResponse);

sub main();
sub calculate_adjustment();
sub reset_clock_params();
sub configDriftValue();
sub check_drift($);

## Allowed correction value range [sec]
my $MIN_DRIFT = -300;
my $MAX_DRIFT = 300;

my %data = (
            'drift' => "",
            'tick'  => "",
            'freq'  => ""
           );

exit(main());

## @fn main()
# @brief Entry point.
# @details
# @param None
# @return $OK - on success
# @return $ERROR - on error
# @author Maxim Uvarov
# @date May 2008
sub main()
{
   my ($i, $n, $date, $helpflag, $showflag, $resetflag, $drift);

   $n = scalar(@ARGV);

   if ($n > 0)
   {

      if (
          !GetOptions(
                      "help"    => \$helpflag,
                      "show"    => \$showflag,
                      "reset"   => \$resetflag,
                      "drift:f" => \$data{'drift'}
                     )
         )
      {
         print_pod_usage();
         return $ERROR;
      } ## end if (!GetOptions("help"...

      if ($n == 1)
      {
         if ($helpflag)
         {
            print_pod_usage();
            return $OK;
         }
         elsif ($showflag)
         {
            print_clock_params();
            return $OK;
         }
         elsif ($resetflag)
         {
            reset_clock_params();
            return $OK;
         }
      } ## end if ($n == 1)

      if ($data{'drift'})
      {
         if (!check_drift($data{'drift'}))
         {
            baselog($LOG_ERROR, "Time adjustment is too huge to apply", $TRUE);
            return $ERROR;
         }
      } ## end if ($data{'drift'})
      else
      {
         print_pod_usage();
         return $ERROR;
      }
   } ## end if ($n > 0)
   else
   {
      ## Interactive mode
      if (configDriftValue() == $FALSE)
      {
         baselog($LOG_ERROR, "Time correction ignored", $TRUE);
         return $ERROR;
      }
   } ## end else [ if ($n > 0)

   ## Do not adjust clock if entered drift equals to zero
   if ($data{'drift'} == 0)
   {
      return $OK;
   }

   ## Calculate how much to adjust the clock
   if (calculate_adjustment() != $TRUE)
   {
      baselog($LOG_ERROR, "Time correction ignored", $TRUE);
      return $ERROR;
   }

   # Make the correction
   if (clock_adjustment_set($data{'tick'}, $data{'freq'}) != $TRUE)
   {
      baselog($LOG_ERROR, "Failed setup time correction", $TRUE);
      return $ERROR;
   }

   # Skip print if non interactive mode
   if ($n == 0)
   {
      print_clock_params();
   }

   ## Save parameter in xml to survive reboot
   if (clock_file_save($data{'tick'}, $data{'freq'}, $data{'drift'}) != $TRUE)
   {
      baselog($LOG_ERROR, "Save parameters failed. Adjustment will not survive reboot", $TRUE);
      return $ERROR;
   }

   return $OK;
} ## end sub main()

## @fn calculate_adjustment()
# @brief This subroutine calculate clock parameters
# @details
# @param None
# @return $TRUE - on success
# @return $FALSE - on error
# @author Maxim Uvarov
# @date May 2008
sub calculate_adjustment()
{

   #Check if correction is too huge to apply
   if (!check_drift($data{'drift'}))
   {
      baselog($LOG_ERROR, "Time adjustment is too huge to apply", $TRUE);
      return $FALSE;
   }

   # New value of tick
   my $tick = int($data{'drift'} / $SEC_TICK);
   $data{'tick'} = $MSEC_PTICK - $tick;

   # Required frequency
   $data{'freq'} = int(((2**16) * ($tick * $SEC_TICK - $data{'drift'})) / ($SEC_TICK / 100));

   return $TRUE;
} ## end sub calculate_adjustment()

## @fn check_drift($)
# @brief This subroutine check entered drift value
# @details
# @param drift value
# @return $TRUE - on success
# @return $FALSE - on error
# @author Maxim Uvarov
# @date May 2008
sub check_drift($)
{
   my $drift = shift(@_);
   return (($drift < $MIN_DRIFT or $drift > $MAX_DRIFT) ? $FALSE : $TRUE);
}

## @fn configDriftValue()
# @brief This subroutine check entered drift value
# @details Queries the user for the drift correction value - allows
#          the user to keep the current correction value or
#          allows him to set it or reset to default values.
# @param None
# @return $TRUE - on success
# @return $FALSE - on error
# @author Maxim Uvarov
# @date May 2008
sub configDriftValue()
{
   my ($action, $opt);

   header('System clock adjustment');
   while ($TRUE)
   {
      print "\nWhat action do you want to do:\n\n";
      print "  1) Adjust system clock with drift per day value\n";
      print "  2) Reset system clock correction to default value\n";
      print "  3) Quit\n";
      print "\nSelect an option (1-3): ";
      chomp($action = <STDIN>);

      if ($action eq '1')
      {
         while ($TRUE)
         {
            print_clock_params();
            if (!getYNResponse("Do you want to keep this correction", 'Y'))
            {
               print "\n";
               while ($TRUE)
               {
                  print "Enter the new correction value between $MIN_DRIFT.0 and $MAX_DRIFT.0 [sec]: ";
                  chomp($opt = <STDIN>);

                  if (   ($opt ne "")
                      && ($opt =~ /^[+-]?\d+\.?\d*$/)
                      && ($opt >= $MIN_DRIFT)
                      && ($opt <= $MAX_DRIFT))
                  {
                     printf "\n\nYou entered: %.3f\n\n", $opt;
                     if (getYNResponse("Do you want to adjust system clock with this value", 'Y'))
                     {
                        $data{'drift'} = $opt;
                        $data{'tick'}  = $MSEC_PTICK;
                        $data{'freq'}  = 0;
                        print "\n";
                        return $TRUE;
                     } ## end if (getYNResponse("Do you want to adjust system clock with this value"...
                     else
                     {
                        $data{'drift'} = 0;
                        return $TRUE;
                     }
                     print "\n";
                  } ## end if (($opt ne "") && ($opt...
                  else
                  {
                     $data{'drift'} = 0;
                     print "\nERROR: Invalid Entry - please enter a value between $MIN_DRIFT and $MAX_DRIFT [sec]\n\n";
                  }
               } ## end while ($TRUE)
            } ## end if (!getYNResponse("Do you want to keep this correction"...
            else
            {
               $data{'drift'} = 0;
               last;
            }
         } ## end while ($TRUE)
         last;
      } ## end if ($action eq '1')
      elsif ($action eq '2')
      {
         print "\n";
         if (getYNResponse("Do you realy want to reset system clock adjustment to default values", 'N'))
         {
            reset_clock_params();
            print_clock_params();
         }
         $data{'drift'} = 0;
         last;
      } ## end elsif ($action eq '2')
      elsif ($action eq '3')
      {
         $data{'drift'} = 0;
         last;
      }
      else
      {
         print "Incorrect entry. Please try again.\n";
      }
   } ## end while ($TRUE)

   return $TRUE;
} ## end sub configDriftValue()

1;

__END__
