#!/usr/bin/perl
################################################################
# @file    hostconfig
# @brief   This script is used to configure hosts
# @author  Kushal Agarwal
# @date:   August 2007
# @version 1.00 - Initial version
# @version 1.01 - POD section was added; the usage is displayed by the
#          common function - print_pod_usage() now.
# @version 1.02 - Two colons were removed before shared functions and variables.
# @version 1.03 - functions validateHostname and validateFQDN were moved to base_validate.pm module
#          by Ekaterina Bazhanova
# @version 1.04 - "print_pod_usage" is changed for "print" in case
#               of error situation.
# @version 1.05 - new mode '-long' support has been added for hostconfig show option

=pod

=head1 NAME

B<hostconfig> - configure the static lookup table for host names.

=head1 SYNOPSIS

=over 4

=item B<hostconfig> [B<-h, --help>]

=item B<hostconfig> [B<add> [-ip <ip>] [-host <hostname>] [-domain <domain>]]

=item B<hostconfig> [B<add> [-ip <ip>] [-fqdn <fqdn>]]

=item B<hostconfig> [B<del> [-ip <ip>] [-host <hostname>] [-domain <domain>]]

=item B<hostconfig> [B<del> [-ip <ip>] [-fqdn <fqdn>]]

=item B<hostconfig> [B<del> [index number]]

=item B<hostconfig> [B<show> [-long]]

=back

=head1 DESCRIPTION

Hostconfig is a system level command used to modify the system hosts database.
This command allows users to add and delete hosts to the system.
It can also be used to view all the hosts configured on the system using this command.

=head1 OPTIONS

=over 4

=item B<-h, --help>

Print a brief help message and exit.

=item B<add> I<parameters>

Add a host to the system host database.  The host can be added either using 2 parameters or 3 parameters.


For 2 pararmeters the IP-Addres and the FQDN (Fully Qualified Domain Name = Hostname + Domain) are required,
the entry in the database will look as follow:
     IP-Address     FQDN

For 3 parameters the IP-Address, the Hostname and the Domain Name are required,
the entry in the database will look as follows:
     IP-Address     FQDN     Hostname

=item B<del> I<parameters>

Delete a host from the system host database.  A host can be delete in one of 3 ways, using 2 parameters, 3 parameters or an index number.

For 2 pararmeters the IP-Addres and the FQDN (Fully Qualified Domain Name = Hostname + Domain) are required.

For 3 parameters the IP-Address, the Hostname and the Domain Name are required.

For the index number, this is the host number printed by the B<show> option.

=item B<show> <parameters>

Show all the hosts configured using B<hostconfig>.  The index number printed can also be used to delete hosts.
The -long option allows to show hosts with long hostnames. By default there will defined limitation in 26 symbols. 
Hosts are shown in the following format:
     Host#     IP-Address     Hostname     Domain

=back

=head1 EXAMPLES

=over 4

=item B<$ hostconfig> add -ip 1.1.1.1 -host testhost -domain ca.nortel.com

    Synchronizing the system host database file                [  OK  ]
    Host succesfully added

=item B<$ hostconfig> add -ip 1.1.1.2 -fqdn testhost2.ca.nortel.com

    Synchronizing the system host database file                [  OK  ]
    Host succesfully added

=item B<$ hostconfig> add -host testhost3 -domain ca.nortel.com -ip 1.1.1.3

    Synchronizing the system host database file                [  OK  ]
    Host succesfully added

=item B<$ hostconfig> show

    Hosts Table (user configured hosts)
    HOST#   IP Address         Hostname                     Domain
    1       1.1.1.1            testhost                     ca.nortel.com
    2       1.1.1.2            testhost2.ca.nortel.com
    3       1.1.1.3            testhost3                    ca.nortel.com

=item B<$ hostconfig> del 1

    Synchronizing the system host database file                [  OK  ]
    Host succesfully deleted

=item B<hostconfig> del -ip 1.1.1.2 -fqdn testhost2.ca.nortel.com

    Synchronizing the system host database file                [  OK  ]
    Host succesfully deleted

=item B<hostconfig> del -ip 1.1.1.3 -host testhost3 -domain ca.nortel.com

    Synchronizing the system host database file                [  OK  ]
    Host succesfully deleted

=back

=cut

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

use warnings;
use strict;

use Getopt::Long;

use common_variables;
use common_functions;
use baselog;
use CommonInstallUtils qw(validateIP);
use hostControl;
use base_validate qw(validateHostname validateDomain validateFQDN);

sub main();

my %data = (
            'ip'     => "",
            'host'   => "",
            'domain' => ""
           );

my %fqdn_data = (
                 'ip'   => "",
                 'fqdn' => ""
                );

#Hash with reference to functions for validating
my %valid_data = (
                  'ip'     => \&validateIP,
                  'host'   => \&validateHostname,
                  'domain' => \&validateDomain
                 );

my %valid_fqdn_data = (
                       'ip'   => \&validateIP,
                       'fqdn' => \&validateFQDN
                      );

exit(main());

###############################################################################
## @fn    main
# @brief  The main fucntion in the script and the entry
#         point when the hostconfig command is invoked.
# @param  cmd - command to execute (add|del|shwo)
#           add|del:  ip - ip address of host
#                     host - hostname
#                     domain - domain name of host
#           del:  index - index number of host (for del option)
#           show: none
# @return $OK  - command was successful
# @return $ERROR - command had errors
sub main()
{
   my ($cmd, $index);
   my $is_fqdn = $FALSE;

   my $host = new hostControl;
   unless (defined $host)
   {
      baselog($LOG_ERROR, "Cannot create HostControl object");
      print "Failed to create HostControl object. Cannot modify hosts.\n";
      return $ERROR;
   } ## end unless (defined $host)

   if ((!defined @ARGV))
   {
      baselog($LOG_ERROR, "Incorrect number of arguments provided\n", $TRUE);
      print_pod_usage();
      return $ERROR;
   } ## end if ((!defined @ARGV))
   elsif (($ARGV[0] eq "-h") || ($ARGV[0] eq "--help"))
   {
      print_pod_usage();
      return $OK;
   }

   $cmd = $ARGV[0];
   if ($cmd =~ /^(add|del)$/)
   {
      my $count = scalar(@$host);
      if (($cmd eq "del") && (defined $ARGV[1]) && ($ARGV[1] =~ /^\d+$/))
      {
         if (($count > 0) && ($ARGV[1] > 0) && ($ARGV[1] <= $count))
         {
            $index = $ARGV[1];
         }
         else
         {
            print "Incorrect host index value.\n";
            return $ERROR;
         }
      } ## end if (($cmd eq "del") &&...
      elsif (scalar(@ARGV) == 7)
      {
         GetOptions(\%data, 'ip=s', 'host=s', 'domain=s');
      }
      elsif (scalar(@ARGV) == 5)
      {
         GetOptions(\%fqdn_data, 'ip=s', 'fqdn=s');
         $is_fqdn = $TRUE;
      }
      else
      {
         print "Incorrect number of parameters.\n";
         return $ERROR;
      }
   } ## end if ($cmd =~ /^(add|del)$/...
   elsif (($cmd eq 'show') && (!defined $ARGV[1]))
   {
      $host->show();
      return $OK;
   }
   elsif (($cmd eq 'show') && (!defined $ARGV[2]))
   {
      my $long = undef;
      GetOptions("long" => \$long);
      if (!defined $long)
      {
         baselog($LOG_ERROR, "Incorrect value for $cmd argument provided\n", $TRUE);
         print_pod_usage();
         return $ERROR;
      }
      $host->show($long);
      return $OK;
   }    
   elsif ($cmd eq 'sync')
   {
      if (!$host->sync())
      {
         print "Failed to synchronize the hosts!\n";
         return $ERROR;
      }
      print "Synchronization complete!\n";
      return $OK;
   } ## end elsif ($cmd eq 'sync')
   else
   {
      baselog($LOG_ERROR, "Incorrect value for $cmd argument provided\n", $TRUE);
      print_pod_usage();
      return $ERROR;
   } ## end else [ if ($cmd =~ /^(add|del)$/...

   #next checking is common code for both add and del command options
   unless (defined $index)
   {

      # Check values
      if ($is_fqdn)
      {
         foreach my $key (keys(%fqdn_data))
         {
            if (!$valid_fqdn_data{$key}($fqdn_data{$key}))
            {
               print "Incorrect value for '$key' parameter\n";
               return $ERROR;
            }
         } ## end foreach my $key (keys(%fqdn_data...
      } ## end if ($is_fqdn)
      else
      {
         foreach my $key (keys(%data))
         {
            if (!$valid_data{$key}($data{$key}))
            {
               print "Incorrect value for '$key' parameter\n";
               return $ERROR;
            }
         } ## end foreach my $key (keys(%data...
      } ## end else [ if ($is_fqdn)
   } ## end unless (defined $index)

   if ($is_fqdn)
   {
      $data{ip}     = $fqdn_data{ip};
      $data{host}   = $fqdn_data{fqdn};
      $data{domain} = "";
   } ## end if ($is_fqdn)

   signals_ignore();

   if ($cmd eq "add")
   {
      if (!$host->add(\%data))
      {
         print "Failed to add host!\n";
         return $ERROR;
      }
   } ## end if ($cmd eq "add")
   elsif ($cmd eq "del")
   {
      if (defined $index)
      {
         if (!$host->del($index))
         {
            print "Failed to delete host!\n";
            return $ERROR;
         }
      } ## end if (defined $index)
      else
      {
         if (!$host->del(\%data))
         {
            print "Failed to delete host!\n";
            return $ERROR;
         }
      } ## end else [ if (defined $index)
   } ## end elsif ($cmd eq "del")

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