#!/usr/bin/perl
################################################################
# @file routeconfig
#
# @brief This script is used to configure routes
#
# @author Peter Kascheev
# @author Pavel Sergeev
# @author Alex Arkhipov
# @author Ilya Bayler
#
# @date:   April 2007
#
# @version 1.00 - Initial version
# @version 2.00 - Using RouteControl class added
# @version 2.01 - POD section was added; the usage is displayed by the
#                 common function - print_pod_usage() now.
# @version 2.10 - the '-host' option support is added
# @version 2.11 - Two colons were removed before shared functions and variables.
# @version 2.12 - "print_pod_usage" is changed for "print" in case
#                  of error situation. POD documentation changed.
# @version 2.20 - new "-tag <app_tag>" option support is added
# @version 2.21 - Changed "-tag <app_tag>" option usage for del command
################################################################

=pod

=head1 NAME

B<routeconfig> - tool to configure routing table.

=head1 SYNOPSIS

=over 4

=item B<routeconfig> B<-h, --help>

=item B<routeconfig> B<add> -net | -host target_ip [-gw <gateway_ip>] [-netmask <mask>] [-dev <eth>] [-tag <tag>]

=item B<routeconfig> B<del> -net | -host target_ip [-gw <gateway_ip>] [-netmask <mask>] [-dev <eth>]

=item B<routeconfig> B<del> <index_number>

=item B<routeconfig> B<del> -tag <tag>

=item B<routeconfig> B<show> [B<-all>] [B<-n>] [B<-tag>]

=back

=head1 DESCRIPTION

B<routeconfig> tool is used to configure routing table. It can add, delete 
and show the routes, configured on the system.
When eth0 options provided ELAN gateway will be used, eth1 - means TLAN gateway will be used.
If gateway option is not provide, then default gateway for device is used

=head1 OPTIONS

=over 4

=item B<-h, --help>

Print this help message and exit.

=item B<show>

Without options - show only user configured routes.

=over 4

=item B<-all>

Show all system and user configured routes.

=item B<-n>

Show numerical addresses instead of symbolic ones.

=item B<-tag> I<tag_name>

Show routes with specified tag only.

=back

=item B<target_ip>

The destination network or host. User can provide IP addresses or network/host names.

=item B<del>

Delete a route

=item B<add>

Add a new route.

=over 4

=item B<-net> I<target_ip>

The target_ip is a network.

=item B<-host> I<target_ip>

The target_ip is a host.

=item B<-gw> I<gateway_ip>

Route packets via gateway. The specified gateway must be reachable.

=item B<-netmask> I<mask>

Netmask must be used only when adding a network entry.

=item B<-dev> I<eth0/eth1/..>

eth0 - ELAN; eth1 - TLAN

=item B<-tag> I<tag_name>

Add route with tag_name. If missing 'base' tag_name is used

=back

=back

=over 4

=item B<del>

Delte the route.

=over 4

=item B<-tag> I<tag_name>

Delete all roures with specified tag. This option must not be used along with other options for B<del> command. 

=item B<-net> I<ip>

Network ip address.

=item B<-gw> I<gateway>

Gateway.

=item B<-netmask> I<mask>

Network mask.

=item B<-dev> I<eth0/eth1/..>

eth0 - ELAN; eth1 - TLAN

=item [I<number>]

Also del command supports deleting routes by number, which B<routeconfig show> prints.

=back

=back

=head1 EXAMPLES

=over 4

=item B<$ routeconfig> show

 Kernel IP routing table (user configured routes)
 ROUTE#   Destination       Gateway           Netmask            Iface  Tag
 1        192.168.35.2      192.168.35.1      255.255.255.255    eth0   base
 2        192.168.35.0      192.168.35.1      255.255.255.0      eth0   base
 3        192.168.35.3      192.168.35.1      255.255.255.255    eth0   ss

=item B<$ routeconfig> add -net 192.168.0.0 -gw 192.168.35.1 -netmask 255.255.0.0 -dev eth1 -tag ss

 Route succesfully added

=item B<$ routeconfig> show

 Kernel IP routing table (user configured routes)
 ROUTE#   Destination       Gateway           Netmask            Iface  Tag
 1        192.168.35.2      192.168.35.1      255.255.255.255    eth0   base
 2        192.168.35.0      192.168.35.1      255.255.255.0      eth0   base
 3        192.168.35.3      192.168.35.1      255.255.255.255    eth0   ss
 4        192.168.0.0       192.168.35.1      255.255.0.0        eth1   ss

=item B<$ routeconfig> del -net 192.168.0.0 -gw 192.168.35.1 -netmask 255.255.0.0 -dev eth1

 Route succesfully deleted

=item B<$ routeconfig> show

 Kernel IP routing table (user configured routes)
 ROUTE#   Destination       Gateway           Netmask            Iface  Tag
 1        192.168.35.2      192.168.35.1      255.255.255.255    eth0   base
 2        192.168.35.0      192.168.35.1      255.255.255.0      eth0   base
 3        192.168.35.3      192.168.35.1      255.255.255.255    eth0   ss

=item B<$ routeconfig> add -host 192.168.35.4 -gw 192.168.35.1 -dev eth1

 Route succesfully added

=item B<$ routeconfig> show

 Kernel IP routing table (user configured routes)
 ROUTE#   Destination       Gateway           Netmask            Iface  Tag
 1        192.168.35.2      192.168.35.1      255.255.255.255    eth0   base
 2        192.168.35.0      192.168.35.1      255.255.255.0      eth0   base
 3        192.168.35.3      192.168.35.1      255.255.255.255    eth0   ss
 4        192.168.35.4      192.168.35.1      255.255.255.255    eth1   base

=item B<$ routeconfig> del -host 192.168.35.4 -gw 192.168.35.1 -dev eth1

 Route succesfully deleted

=item B<$ routeconfig> show

 Kernel IP routing table (user configured routes)
 ROUTE#   Destination       Gateway           Netmask            Iface  Tag
 1        192.168.35.2      192.168.35.1      255.255.255.255    eth0   base
 2        192.168.35.0      192.168.35.1      255.255.255.0      eth0   base
 3        192.168.35.3      192.168.35.1      255.255.255.255    eth0   ss

=item B<$ routeconfig> del -tag ss

 Route(3) succesfully deleted

=item B<$ routeconfig> show

 Kernel IP routing table (user configured routes)
 ROUTE#   Destination       Gateway           Netmask            Iface  Tag
 1        192.168.35.2      192.168.35.1      255.255.255.255    eth0   base
 2        192.168.35.3      192.168.35.1      255.255.255.255    eth0   base

=back

=head1 CAVEATS

B<routeconfig>  can be run only under Nortel authorized accounts.

=cut

use warnings;
use strict;

use Getopt::Long;

use lib '/opt/nortel/base/lib';

use common_variables;
use common_functions;
use install_common;
use baselog;
use CommonInstallUtils qw(validateIP);
use RouteControl;

sub main();
sub validateDev($);
sub dummyCheck($);

# Hash which will contain input data
my %data = ();

# Hash with reference to functions for validating
my %valid_data = (
                  'net'     => \&validateIP,
                  'host'    => \&validateIP,
                  'gw'      => \&validateIP,
                  'netmask' => \&validateIP,
                  'dev'     => \&validateDev,
                  'tag'     => \&dummyCheck
                 );

exit(main());

sub main()
{
   if (warning_if_not_root_uid())
   {
      return $ERROR;
   }

   my $route = new RouteControl;
   if (not defined $route)
   {
      baselog($LOG_ERROR, 'Can not create RouteControl object');
      return $ERROR;
   }

   my ($cmd, $route_cmd, $res, $index);

   if (not defined @ARGV)
   {
      baselog($LOG_ERROR, "Incorrect number of arguments provided\n", $TRUE);
      print_pod_usage();
      return $ERROR;
   } ## end if (not defined @ARGV)
   elsif (($ARGV[0] eq '-h') || ($ARGV[0] eq '--help'))
   {
      print_pod_usage();
      return $OK;
   }
   else
   {
      $cmd = $ARGV[0];
      if ($cmd =~ /^(add|del)$/)
      {
         if (($cmd eq 'del') && (defined $ARGV[1]) && ($ARGV[1] =~ /^\d+$/))
         {
            if ($ARGV[1] > 0)
            {
               $index = $ARGV[1];
            }
            else
            {
               print "Incorrect route index value.\n";
               return $ERROR;
            }
         } ## end if (($cmd eq 'del') &&...
         else
         {
            $res = GetOptions(\%data, 'net=s', 'host=s', 'gw=s', 'netmask=s', 'dev=s', 'tag=s');
            if (!$res)
            {
               print_pod_usage();
               return $ERROR;
            }

            if (($cmd eq 'del') && (exists($data{'tag'})) && (scalar(keys(%data)) > 1))
            {
               print "The -tag option can not be used along with other for 'del' command (see routeconfig --help)\n";
               return $ERROR;
            }
            elsif (($cmd ne 'del') && not exists($data{'tag'}))
            {
               $data{'tag'} = $DEFAULT_ROUTE_TAG;
            }
            if (not(($cmd eq 'del') and exists($data{'tag'})) and not exists($data{'dev'}))
            {
               $data{'dev'} = '';
            }

            # Command line arguments checking (net, host, netmask)
            if (exists($data{'net'}) && exists($data{'host'}))
            {
               print "The -net and the -host options can't be used at once (see routeconfig --help)\n";
               return $ERROR;
            }
            elsif ((not exists($data{'net'})) && (not exists($data{'host'})) && (not exists($data{'tag'})))
            {
               print "Please specify -net or -host option (see routeconfig --help)\n";
               return $ERROR;
            }
            elsif (exists($data{'host'}) && exists($data{'netmask'}))
            {
               print "The -host option must be used without the -netmask (see routeconfig --help)\n";
               return $ERROR;
            }
            elsif (exists($data{'net'}) && (not exists($data{'netmask'})))
            {
               print "The -net option must be used with the -netmask (see routeconfig --help)\n";
               return $ERROR;
            }
            if ($cmd eq 'add')
            {
               if ((not exists($data{'net'})) && (not exists($data{'host'})))
               {
                  print "Please specify -net or -host option (see routeconfig --help)\n";
                  return $ERROR;
               }
            } ## end if ($cmd eq 'add')
            else
            {
               if (not exists($data{'tag'}))
               {
                  if ((not exists($data{'net'})) && (not exists($data{'host'})))
                  {
                     print "Please specify -net or -host option (see routeconfig --help)\n";
                     return $ERROR;
                  }
               } ## end if (not exists($data{'tag'...
            } ## end else [ if ($cmd eq 'add')
         } ## end else [ if (($cmd eq 'del') &&...
      } ## end if ($cmd =~ /^(add|del)$/...
      elsif ($cmd eq 'show')
      {
         my ($arg, $all, $opt_n) = (undef, undef, undef, undef);
         my %d = ('tag' => undef);

         $res = GetOptions(\%d, 'tag=s', 'all' => \$all, 'n' => \$opt_n);
         if (!$res)
         {
            print_pod_usage();
            return $ERROR;
         }

         if (defined $d{'tag'})
         {
            $arg = $d{'tag'};
         }
         elsif (defined($all))
         {
            $arg = $ALL_ROUTES;
            if (defined $opt_n)
            {
               $opt_n = '-n';
            }
         } ## end elsif (defined($all))
         elsif (defined $ARGV[1])
         {
            print "Incorrect $cmd command value $ARGV[1].\n";
            return $ERROR;
         }
         $route->show($arg, $opt_n);
         return $OK;
      } ## end elsif ($cmd eq 'show')
      else
      {
         baselog($LOG_ERROR, "Incorrect command $cmd provided\n", $TRUE);
         print_pod_usage();
         return $ERROR;
      } ## end else [ if ($cmd =~ /^(add|del)$/...
   } ## end else [ if (not defined @ARGV)

   # Some checking. Common code for both 'add' and 'del' w|o '-tag' command options
   if (($cmd eq 'add') or ($cmd eq 'del' and not exists($data{'tag'}) and not defined($index)))
   {

      # Check values
      foreach my $key (keys(%data))
      {
         if ($data{$key} eq "")
         {
            print "Incorrect parameters provided $key\n";
            print_pod_usage();
            return $ERROR;
         } ## end if ($data{$key} eq "")
         if (!$valid_data{$key}($data{$key}))
         {
            print "Incorrect value for '$key' parameter\n";
            print "Try `routeconfig --help' for more information\n";
            return $ERROR;
         } ## end if (!$valid_data{$key}...
      } ## end foreach my $key (keys(%data...
   } ## end if ((not defined $index...

   signals_ignore();

   my $ret_val = $TRUE;
   my $command = 'manage';

   if ($cmd eq 'add')
   {
      $command = 'add';
      $ret_val = $route->add(\%data);
   }
   elsif ($cmd eq 'del')
   {
      $command = 'delete';
      if (defined $index)
      {
         $ret_val = $route->del($index);
      }
      else
      {
         $ret_val = $route->del(\%data);
      }
   } ## end elsif ($cmd eq 'del')

   undef $route;

   if (not $ret_val)
   {
      print "Failed to $command route!\n";
      return $ERROR;
   }

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

## @fn validateDev($dev)
# @brief check if $dev is valid network device
# @details check for matching to "eth*" pattern
# @param $dev - device name to check
# @return $TRUE  - device is valid
# @return $FALSE - device is not valid
sub validateDev($)
{
   my $dev = shift(@_);
   if ((not defined($dev)) or ($dev !~ /^eth\d+$/))
   {
      return $FALSE;
   }
   return $TRUE;
} ## end sub validateDev($)

## @fn dummyCheck($param)
# @brief emulates check
# @details always return $TRUE
# @param $param - param to check
# @return $TRUE
sub dummyCheck($)
{
   return $TRUE;
}
