#!/usr/bin/perl
## @file basesettime
# @brief Tool to set new time which comes from CS.
#        The tool is provided with Linux Base and used
#        by both CS and PBX (SS).
# @details The tool checks whether we can set new time or not.
#          It calls ntpconfig to find out the current status of
#          NTP. If NTP is configured as NTP client to take time
#          from external servers, then the tool rejects the time.
#          Otherwise it sets the time.
#          Usage: basesettime <YEAR> <MON> <DAY> <HRs> <MINs> <SECs>
#             Ex: basesettime 2008 12 4 9 49 11
# @author Sergey Balabanov
# @date December 2008
# @version 1.00 - Initial version

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

use warnings;
use strict;

use common_variables;
use base_system;
use baselog;
use baseParams;

my $NTPCONFIG_BIN = "/opt/nortel/base/bin/ntpconfig";

sub main();
exit(main());

###############################################################################
## @fn    main
# @brief  The main fucntion in the script and the entry
#         point when the basesettime command is invoked.
# @return $OK  - command was successful
# @return $ERROR - command had errors
sub main()
{
   if (($#ARGV + 1) != 6)
   {

      # We don't have to print help usage since the tool
      # is not intended to be used by the customer.
      # But do log incorrect usage of the tool.
      baselog($LOG_ERROR, "Incorrect usage of basesettime tool.", $TRUE);
      return $ERROR;
   } ## end if (($#ARGV + 1) != 6)

   my $ret_val = $NOT_TIME_RECIPIENT;
   if (do_sudo([$NTPCONFIG_BIN, "-is_time_recipient"], {$dsRETVAL => \$ret_val, $dsNOERROR => $TRUE}) != $TRUE)
   {
      baselog($LOG_ERROR, "ntpconfig has exited with error status.");
      return $ERROR;
   }

   if ($ret_val == $TIME_RECIPIENT)
   {

      # ntpconfig says that either NTP Client or NTP Server is configured.
      baselog($LOG_INFO, "New time is not applied because the server is either NTP Client or NTP Server.", $TRUE);
      return $OK;
   } ## end if ($ret_val == $TIME_RECIPIENT...
   elsif ($ret_val == $NOT_TIME_RECIPIENT)
   {
      if (do_sudo([$SUDO_NORTEL, "time_setup", $ARGV[0], $ARGV[1], $ARGV[2], $ARGV[3], $ARGV[4], $ARGV[5]]) != $TRUE)
      {
         baselog($LOG_ERROR, "time_setup is not executed properly.");
         return $ERROR;
      }
   } ## end elsif ($ret_val == $NOT_TIME_RECIPIENT...
   else
   {
      baselog($LOG_ERROR, "ntpconfig has returned unexpected status value ($ret_val).", $TRUE);
      return $ERROR;
   }

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

