#!/usr/bin/perl
## @file ntpconfig
# @brief This script configures NTP settings
# @details If there are no cli arguments provided then
#          user will be prompted to enter them
# @author Alex Arkhipov
# @date January 2007
# @version 1.00 - Initial version
# @version 1.01 - Help printing was added by Kate Pestova
# @version 1.02 - POD section was added; the usage is
#                 displayed by the common function -
#                 print_pod_usage() now.
# @version 1.03 - Two colons were removed before shared functions and variables.
# @version 1.04 - Control of user input is added. Special characters are allowed
#                 for NTP private key in non-interactive mode.
# @version 1.05 - Remove CSSync option, implement automatic ntpd service restart
# @version 1.06 - fixed issue when for "Not a clock Server" external IPs are not
#                 printed.
# @version 1.07 - Man-page was changed (single quotes for private key, # space '
#                 denied).
# @version 1.08 - fixed issue when for "Not a clock Server" peer are printed.
# @version 1.09 - added option to disable or enable ntpd panic on big time delta
# @version 1.10 - Invocation of validateNTPconfiguration() was added.
# @version 1.11 - Introduced new flag named is_time_recipient (not for the customer usage!)
# @version 1.12 - fixed issue with is_time_recipient option
# @version 1.13 - new command ntpsync is supported; --syncnow options added
# @version 1.14 - Invocation of validateNTPconfiguration() was moved
# @version 1.15 - 'peer' option has been removed.
# @version 1.16 - POD documentation has been changed.

=pod

=head1 NAME

B<ntpconfig> - configures the Network Time Protocol settings.

=head1 SYNOPSIS

B<ntpconfig> [B<--show>] [B<-cl_type> I<< <0-1> >>] [B<-src_type> I<< <0-2> >>] [B<-smode> I<< <y/n> >>] [B<-keyid> I<id>]
[B<-clIPs> I<IPs>] [B<-prikey> I<key>] [B<-enl_panic>] | [B<--help>]

=head1 DESCRIPTION

This command configures NTP settings. If there are no cli arguments provided, 
then user will be prompted to enter them. NTP deamon will be restarted 
automatically.

The Network Time Protocol is widely used to synchronize computer clocks in the 
global IP network. NTP runs over the User Datagram Protocol (UDP). An NTP
network usually gets its time from an authoritative time source, such as a
radio clock or an atomic clock attached to a time server. NTP then distributes
this time across the network.

NTP hierarchy copies the routing hierarchy. Core routers have a client/server
relationship with external time sources, the internal time servers have a
client/server relationship with the core routers, the internal customer
(non time servers) routers have a client/server relationship with the internal
time servers, and so on down the tree.

Ntpconfig supports secure mode, using MD5 algorithm.
The MD5 algorithm is intended for digital signature applications, where
a large file must be "compressed" in a secure manner before being encrypted
with a private (secret) key under a public-key cryptosystem such as RSA.

=head1 OPTIONS

=over 4

=item B<--show>

Show the current network settings.

=item B<-cl_type>  I<< <0-1> >>

Clock type (0-EXTERNAL, 1-INTERNAL)

=item B<-src_type> I<< <0-2> >>

Clock source type (0-Primary,1-Secondary,2-Not a clock server)

=item B<-smode> I<< <Y/N> >>

Secure mode (Y/N)

=item B<-keyid> I<< <id> >>

NTP (in secure MD5 transfer mode) key ID. NTP key ID should be between 1 ~ 65535.

=item B<-clIPs> I<IPs>

Clock IPs (string in quotes, IPs are separated by '|' symbol). 
Only two clock IPs are supported if the server is configured as "Not a Clock Server": Primary server IP and Secondary server IP. 

=item B<-prikey> I<< <key> >>

NTP private key (string in single quotes, no more than 16 characters, excluding space, # and ')

=item B<-enl_panic>

If this option is specified ntp daemon will exit if the time delta is greater than 1000s.

=item B<--help>

Print this help message and exit.

=back

=head1 EXAMPLES

$ B<ntpconfig>

 Network Time Protocol (NTP) Configuration
 -----------------------------------------

 Please determine NTP transfer mode within your whole system:
   
   Do you wish to configure NTP in secure MD5 transfer mode? (Y/N) [Y]? y
   Enter the NTP (in secure MD5 transfer mode) key ID [1]: 1
 
 Enter the NTP private key: 
 Enter the NTP private key again: 
 Please indicate the Clock Source function of this Linux system:

   1) Primary Clock Source server (This is the Primary NTP server)
   2) Secondary Clock Source server (another one is the Primary NTP server)
   3) This Linux system is NOT a Clock Source server 
 Select an option (1-3) [1]: 1       

 NTP Clock Source Configuration
 ------------------------------
 The Primary Clock Source server requires the use of an external clock.
 
 Select External Clock for time source(s) external to this server.
 Select Internal Clock to use the local system clock as the time source.

    E - External Clock Source (IP Addresses)
    I - Internal Clock (Unreliable)
    
 Select an option (E, I) [E]: E
 How many external clock sources would you like to reference (1-11) [1]? 1
 External Clock Source IP Address #1 [192.168.35.100]: 192.168.35.100
  
 NTP server configuration:

   NTP is configured in secure MD5 transfer mode:
                          NTP Key ID: 1
                     NTP Private Key: ********
		      
		    NTP Clock Source: Primary
                      NTP Clock Type: External
                      External IP(s): 192.168.35.100
NTP deamon will automatically be restarted now!


$ B<ntpconfig> B<-cl_type> I<0> B<-src_type> I<0> B<-smode> I<Y> B<-keyid> I<1> B<-clIPs> I<"192.168.35.45|192.168.35.46">
B<-prikey> I<'%1Qwerty&'>
 
 NTP server configuration:
 
   NTP is configured in secure MD5 transfer mode:
                          NTP Key ID: 1
                     NTP Private Key: ********
 
                    NTP Clock Source: Primary
                      NTP Clock Type: External
                      External IP(s): 192.168.35.45, 192.168.35.46
NTP deamon will automatically be restarted now! 
 
=head1 CAVEATS

The NTP service deamon will automatically be started after configuration. 

=head1 SEE ALSO

B<baseparamconfig>

=cut

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

use warnings;
use strict;
use Getopt::Long;

use common_variables;
use common_functions;
use CommonInstallUtils;
use baseParams;
use baseParamsUI;
use baselog;
use base_system;

## @skipline
sub main();

# Hash %data for options that user inputs
# Option "is_time_recipient" is used only as flag
# and %base_data should not contain it.
my %data = (
            'cl_type'           => "",
            'src_type'          => "",
            'smode'             => "",
            'keyid'             => "",
            'clIPs'             => "",
            'prikey'            => "",
            'is_time_recipient' => undef
           );

# Hash with matched names for baseParams.pm module
my %matched_data = (
                    'cl_type'   => "clockType",
                    'src_type'  => "clockSourceType",
                    'smode'     => "ntpSecurityMode",
                    'keyid'     => "ntpSecurityModeKeyID",
                    'clIPs'     => "clockIPs",
                    'prikey'    => "ntpSecurityModePriKey",
                    'enl_panic' => "enablePanic"
                   );

# Hash with data to set in baseParams.pm module
# Hash entry "enablePanic" is used to disable ntpd panic on big time delta.
# If it is $FALSE ntpd panic will be diabled and the following line:
# "tinker panic 0" will be added to ntp.conf. Otherwise ntpd will exit if time delta
# is greater than 1000 sec.
my %base_data = (
                 'clockType'             => '',
                 'clockSourceType'       => '',
                 'ntpSecurityMode'       => '',
                 'ntpSecurityModeKeyID'  => '',
                 'clockIPs'              => '',
                 'ntpSecurityModePriKey' => '',
                 'enablePanic'           => $FALSE
                );

exit(main());

###############################################################################
## @fn    main
# @brief  The main fucntion in the script and the entry
#         point when the ntpconfig command is invoked.
# @return $OK  - command was successful
# @return $ERROR - command had errors
# @return $TIME_RECIPIENT - the server is configured as either NTP Server or NTP Client
# @return $NOT_TIME_RECIPIENT - the server is not configured as NTP Server or NTP Client
###############################################################################
sub main()
{
   if (defined $ARGV[0] and $ARGV[0] =~ /help$/)
   {
      print_pod_usage();
      return $OK;
   }

   if (!defined(getParams(\%base_data)))
   {
      baselog($LOG_ERROR, "Cannot get current data", $TRUE);
      return $ERROR;
   }

   # If --syncnow option is provided, do this synchronization only and exit
   if (defined $ARGV[0] and $ARGV[0] eq "--syncnow" and scalar @ARGV == 1)
   {
      my @clocks = split(/\|/, $base_data{'clockIPs'});
      unless (scalar @clocks)
      {
         baselog($LOG_ERROR, "Cannot synchronize time now. No clock IP addresses configured");
         return $ERROR;
      }

      signals_ignore();
      baselog($LOG_INFO, "Synchronizing time with server(s): " . join(' ', @clocks));

      if (!do_system([$NTPDATE, '-u', @clocks]))
      {
         signals_default();
         baselog($LOG_ERROR, "Could not synchronize time now.");
         return $ERROR;
      } ## end if (!do_system([$NTPDATE...
      signals_default();
      return $OK;
   } ## end if (defined $ARGV[0] and...

   # If there are any arguments then try to extract data from arguments
   my $interactive = (scalar(@ARGV) == 0) ? $TRUE : $FALSE;
   if (!$interactive)
   {
      if ((scalar(@ARGV) == 1) && ($ARGV[0] eq "--show"))
      {
         print_ntp_config(\%base_data);
         return $OK;
      }
      my $i = 0;
      while (defined($ARGV[$i]))
      {
         if ($ARGV[$i] !~ /^\-\w+$/)
         {
            print_pod_usage("Incorrect option $ARGV[$i] is provided");
            return $ERROR;
         }
         $i += 2;
      } ## end while (defined($ARGV[$i])...
      my $res = GetOptions(\%data, 'cl_type=i', 'src_type=i', 'smode=s', 'keyid=i', 'clIPs=s', 'prikey=s', 'enl_panic', 'is_time_recipient');
      if (!$res)
      {
         print_pod_usage();
         return $ERROR;
      }

      if ($data{'is_time_recipient'})
      {

         # Block cssync using the followin regularities:
         #
         # *cl_type*     |  *scr_type*             | *cssync*
         # --------------+-------------------------+-------------
         # external (0)  |  Primary            (0) | Block
         # external (0)  |  Secondary          (1) | Block
         # external (0)  |  Not a clock server (2) | Block
         # internal (1)  |  Primary            (0) | Do not block
         # internal (1)  |  Not a clock server (2) | Do not block

         if (!validateParam('clockSourceType', $base_data{'clockSourceType'}))
         {
            print "Wrong clockSourceType value.";
            return $ERROR;
         }

         if ($base_data{'clockType'} == $EXTERNAL_CLOCK)
         {

            # Clock type - EXTERNAL
            return $TIME_RECIPIENT;
         } ## end if ($base_data{'clockType'...
         elsif ($base_data{'clockType'} == $INTERNAL_CLOCK)
         {

            # Clock type - INTERNAL
            return $NOT_TIME_RECIPIENT;
         } ## end elsif ($base_data{'clockType'...
         else
         {
            print "Wrong clockType value.";
            return $ERROR;
         }

         # All that we have to do recieving 'is_time_recipient' flag is
         # return correct state of NTP. It should be done above this line.
         # We do not need to process others parameters. We do not need
         # to do ahything else except what we have already done.
         # That'is why exit with OK status.
         return $OK;
      } ## end if ($data{'is_time_recipient'...
      else
      {
         delete $data{'is_time_recipient'};
      }

      # Check values
      foreach my $key (keys(%data))
      {
         next if ($data{$key} eq "");  # skip empty arguments
         if (!validateParam($matched_data{$key}, $data{$key}))
         {
            print "Incorrect value for '$key' parameter.\n";
            return $ERROR;
         }
      } ## end foreach my $key (keys(%data...

      if (($data{'src_type'} ne $PRIMARY or $data{'cl_type'} eq $EXTERNAL_CLOCK) and not exists $data{'enl_panic'})
      {
         $data{'enl_panic'} = $FALSE;
      }
      else
      {
         $data{'enl_panic'} = $TRUE;
      }

      foreach my $key (keys(%data))
      {
         $base_data{$matched_data{$key}} = $data{$key};
      }

      if (!validateNTPconfiguration(\%base_data))
      {
         return $ERROR;
      }

   } ## end if (!$interactive)

   if ($interactive)
   {  # Prompt user for new network settings
      configNTP(\%base_data);
   }

   print_ntp_config(\%base_data);

   if ($interactive)
   {
      if (!getYNResponse("This setting will override any other clock sources!\nAre you sure you want to continue", "N"))
      {
         baselog($LOG_INFO, "NTP configuration aborted by user!\n", $TRUE);
         return $OK;
      }
   } ## end if ($interactive)

   signals_ignore();
   unless (setupNTP(\%base_data))
   {
      signals_default();
      baselog($LOG_ERROR, "ERROR: Cannot set up NTP settings\n", $TRUE);
      return $ERROR;
   } ## end unless (setupNTP(\%base_data...

   baselog($LOG_INFO, "NTP daemon will automatically be restarted now!", $TRUE);
   if (!do_system([$SERVICE, 'ntpd', $SRV_RESTART]))
   {
      baselog($LOG_ERROR, "Could not restart the NTP deamon!", $TRUE);
   }
   signals_default();
   return $OK;
} ## end sub main()

__END__
