#!/usr/bin/perl


BEGIN {
   push (@INC, "./lib/");
   push (@INC, "../lib/");
   push (@INC, "/usr/lib/sidekick/");
   push (@INC, "/usr/lib64/sidekick/");
}

use Term::ScreenColor;
use Sidekick;
use Getopt::Long;

Getopt::Long::Configure ("bundling", "pass_through");


my $usage = "USAGE: $0 [OPTIONS]...
   About:
      network-config ...

   Options:
    -h, --help      Show this help screen

  This tool is part of cAos - Community Linux
     http://caos.caosity.org/
";


GetOptions(
   'help|h'  => \$help,
   'init'    => \$init,
);

if ( $help ) {
   die $usage;
}

my @netDevs;
chdir("/sys/class/net");
foreach $_ ( glob("*")) {
   if ( $_ !~ /lo|sit\d+/ ) {
      push(@netDevs, $_);
   }
}

sub getModName {
   my ( $dev, @NULL) = @_;
   my $a;
   my $ret = "unmanaged";
   open(MODCONF, "/etc/modprobe.conf");
   foreach $a (<MODCONF>) {
      chomp $a;
      if ( $a =~ /^alias $dev\s+(\S+)$/ ) {
         $ret = $1;
      }
   }
   close MODCONF;
   return $ret;
}

sub writeDNS {
   my ($dns, @NULL) = @_;
   my ($file, $ns);
   open(RESOLV, "< /etc/resolv.conf");
   while (<RESOLV>) {
      chomp;
      if ( $_ =~ /^nameserver / ) {
         if ( ! $ns ) {
            $file .= "nameserver $dns\n";
         }
         $ns = '1';
      } else {
         $file .= "$_\n";
      }
   }
   if ( ! $ns ) {
      $file .= "nameserver $dns\n";
   }
   close RESOLV;
   open(RESOLV, "> /etc/resolv.conf");
   print RESOLV $file;
   close RESOLV;
}

sub readDNS {
   my $ret;
   open(RESOLV, "< /etc/resolv.conf");
   while (<RESOLV>) {
      chomp;
      if ( $_ =~ /^nameserver (.*)$/ ) {
         $ret = $1;
         last;
      }
   }
   return($ret);
}

if ( ! -f "/etc/sysconfig/network" ) {
   open(NETWORK, "> /etc/sysconfig/network");
   print NETWORK "NETWORKING=yes\n";
   print NETWORK "HOSTNAME=localhost\n";
   close NETWORK;
}

my $scr = new Term::ScreenColor;
   unless ($scr) { die "Ack! Couldn't get control of screen!\n"; }
$scr->noecho();
$scr->clrscr();

sub write_page {
   my ( $sel, @NULL) = @_;
   $scr->at(0,0);
   $scr->on_blue();
   $scr->white();
   $scr->puts("cAos Linux: Network Device Configuration Tool:                                  ");
   $scr->normal();
   $line = 2;
   $count = 1;

   $scr->at($line,1);
   $scr->bold();
   $scr->blue();
   $out=sprintf(" %-9.9s  %-15.15s %-6.6s  %-6.6s  %15.15s  %15.15s   ",
         "Device",
         "Kernel Module",
         "OnBoot",
         "Proto",
         "IP address",
         "Netmask");
   $scr->puts($out);
   $scr->normal();
   $line++;
   $count++;

   foreach $dev ( sort @netDevs ) {
      $mac{$dev} = &getMacAddr($dev);
      if ( &NicConnected($dev)) {
         $link = 'Link is active';
      } else {
         $link = 'Link is down';
      }
      if ( $sel == $line ) {
         $message = sprintf("Device: %-10.10s       MAC: %-17.17s           %20.20s", $dev, $mac{$dev}, $link);
         &info_message($scr, $message);
         $scr->at($line,1);
         $scr->reverse();
         $scr->cyan();
         $scr->inverse();
         $curr_entry = "NIC:$dev"
      } else {
         $scr->at($line,1);
         $scr->normal();
      }
      if ( -f "/etc/sysconfig/network-scripts/ifcfg-$dev" ) {
         @{$ifcfg{"$dev"}{array}} = &conf_array("/etc/sysconfig/network-scripts/ifcfg-$dev");
         %{$ifcfg{"$dev"}} = &conf_array_to_hash(@{$ifcfg{"$dev"}{array}});
         $out=sprintf(" %-9.9s  %-15.15s  %-3.3s   %-6.6s  %15.15s  %15.15s   ",
               $dev, 
               &getModName($dev), 
               $ifcfg{$dev}{"ONBOOT"}, 
               $ifcfg{$dev}{"BOOTPROTO"},
               $ifcfg{$dev}{"IPADDR"},
               $ifcfg{$dev}{"NETMASK"});
      } else {
         $out=sprintf(" %-9.9s  %-15.15s  %-3.3s   %-6.6s  %15.15s  %15.15s   ",
               $dev, 
               &getModName($dev), 
               "", 
               "",
               "unconfigured",
               "");
      }
      $scr->puts($out);
      $line++;
      $count++;
      $scr->normal();
   }
   @array = &conf_array("/etc/sysconfig/network");
   %array = &conf_array_to_hash(@array);
   $hostname = $array{"HOSTNAME"};
   $gateway = $array{"GATEWAY"};
   $dns = &readDNS();

#   $line++;
#   $count++;
#   if ( $sel == $line-1 ) {
#      &info_message($scr, "The hostname is the primary name for this system");
#      $scr->at($line,1);
#      $scr->reverse();
#      $scr->cyan();
#      $scr->inverse();
#      $curr_entry = "Hostname"
#   } else {
#      $scr->at($line,1);
#      $scr->normal();
#   }
#   $out=sprintf(" %-23.23s  %-50s", "Hostname:", $array{"HOSTNAME"});
#   $scr->puts($out);

   $line++;
   $count++;
   if ( $sel == $line-1 ) {
      &info_message($scr, "Configure the primary DNS server");
      $scr->at($line,1);
      $scr->reverse();
      $scr->cyan();
      $scr->inverse();
      $curr_entry = "Gateway"
   } else {
      $scr->at($line,1);
      $scr->normal();
   }
   $out=sprintf(" %-23.23s  %-50s", "Gateway:", $array{"GATEWAY"});
   $scr->puts($out);

   $line++;
   $count++;
   if ( $sel == $line-1 ) {
      &info_message($scr, "The domain name server is used for hostname lookup conversions to IP addresses");
      $scr->at($line,1);
      $scr->reverse();
      $scr->cyan();
      $scr->inverse();
      $curr_entry = "DNS"
   } else {
      $scr->at($line,1);
      $scr->normal();
   }
   $out=sprintf(" %-23.23s  %-50s", "Domain name server:", $dns);
   $scr->puts($out);

   $line++;

   $scr->normal();
   $scr->at(21,0);
   $scr->clreol();
   $status_line = 21;
   $scr->cyan();
   $scr->puts("Arrow keys to navigate, space/enter to select, 'd' when done, [ESC] to quit: ");
   $scr->normal();
   return($count);
}

sub mod_entry {
   $scr->clreol();
   if ( $curr_entry =~ /^NIC:(.+)$/ ) {
      &info_message($scr, "Configuring device: $1 (MAC ADDR: $mac{$1})", 1);
      $active = ();
      @networkConf = &conf_array("/etc/sysconfig/network-scripts/ifcfg-$1");
      @networkConf = &change_line("DEVICE", "$1", @networkConf);
      while (1) {
         $scr->at($status_line,0);
         $scr->clreol();
         $scr->puts("Should this device be activated on boot [(y)es/(n)o]: ");
         if ( $ifcfg{$1}{"ONBOOT"} ) {
            $string = &get_str($scr,$status_line,54,'yesno', $ifcfg{$1}{"ONBOOT"});
         } else {
            $string = &get_str($scr,$status_line,54,'yesno', "yes");
         }
         if ( $string =~ /^y(es)?$/ ) {
            $string = 'yes';
            last;
         } elsif ( $string =~ /^n(o)?$/ ) {
            $string = 'no';
            last;
         }
      }
      @networkConf = &change_line("ONBOOT", "$string", @networkConf);
      while (1) {
         $scr->at($status_line,0);
         $scr->clreol();
         $scr->puts("IP address configuration [(d)hcp/(s)tatic]: ");
         if ( $ifcfg{$1}{"BOOTPROTO"} ) {
            $string = &get_str($scr,$status_line,44,'dhcpstati', $ifcfg{$1}{"BOOTPROTO"});
         } else {
            $string = &get_str($scr,$status_line,44,'dhcpstati', "dhcp");
         }
         if ( $string =~ /^d(hcp)?$/ ) {
            $string = 'dhcp';
            last;
         } elsif ( $string =~ /^s(tatic)?$/ ) {
            $string = 'static';
            last;
         }
      }
      @networkConf = &change_line("BOOTPROTO", "$string", @networkConf);
      if ( $string eq 'dhcp' ) {
         @networkConf = &change_line("NETMASK", undef, @networkConf);
         @networkConf = &change_line("IPADDR", undef, @networkConf);
         $hostname =~ /^([a-zA-Z0-9\-_]+)\..*$/;
         $short_hostname = $1;
         @networkConf = &change_line("DHCP_HOSTNAME", $short_hostname, @networkConf);
      } elsif ( $string eq 'static' ) {
         @networkConf = &change_line("DHCP_HOSTNAME", undef, @networkConf);
         while (1) {
            $scr->at($status_line,0);
            $scr->clreol();
            $scr->puts("Static IP address assignment: ");
            $string = &get_str($scr,$status_line,31,'0-9\.', $ifcfg{$1}{"IPADDR"});
            last if ( $string =~ /^\d\d?\d?\.\d\d?\d?\.\d\d?\d?\.\d\d?\d?$/ );
         }
         @networkConf = &change_line("IPADDR", "$string", @networkConf);
         while (1) {
            $scr->at($status_line,0);
            $scr->clreol();
            $scr->puts("Static netmask assignment: ");
            $string = &get_str($scr,$status_line,27,'0-9\.', $ifcfg{$1}{"NETMASK"});
            last if ( $string =~ /^\d\d?\d?\.\d\d?\d?\.\d\d?\d?\.\d\d?\d?$/ );
         }
         @networkConf = &change_line("NETMASK", "$string", @networkConf);
      }
      if ( -d "/sys/class/net/$1/wireless" ) {
         $scr->at($status_line,0);
         $scr->clreol();
         $scr->puts("OPTIONAL: Wireless network domain name (ESSID): ");
         if ( $ifcfg{$1}{"ESSID"} ) {
            $string = &get_str($scr,$status_line,48,'a-zA-Z0-9\-\.', $ifcfg{$1}{"ESSID"});
         } else {
            $string = &get_str($scr,$status_line,48,'a-zA-Z0-9\-\.', "");
         }
         @networkConf = &change_line("ESSID", "$string", @networkConf);
         $scr->at($status_line,0);
         $scr->clreol();
         $scr->puts("OPTIONAL: Wireless network encryption key (WEP): ");
         if ( $ifcfg{$1}{"KEY"} ) {
            $string = &get_str($scr,$status_line,49,'a-zA-Z0-9\-\.', $ifcfg{$1}{"KEY"});
         } else {
            $string = &get_str($scr,$status_line,49,'a-zA-Z0-9\-\.', "");
         }
         @networkConf = &change_line("KEY", "$string", @networkConf);
         if ( ! $ifcfg{$1}{"KEY1"} ) {
            @networkConf = &change_line("KEY1", "", @networkConf);
         }
         if ( ! $ifcfg{$1}{"KEY2"} ) {
            @networkConf = &change_line("KEY2", "", @networkConf);
         }
         if ( ! $ifcfg{$1}{"NICKNAME"} ) {
            @networkConf = &change_line("NICKNAME", "", @networkConf);
         }
         if ( ! $ifcfg{$1}{"NWID"} ) {
            @networkConf = &change_line("NWID", "", @networkConf);
         }
         if ( ! $ifcfg{$1}{"FREQ"} ) {
            @networkConf = &change_line("FREQ", "", @networkConf);
         }
         if ( ! $ifcfg{$1}{"CHANNEL"} ) {
            @networkConf = &change_line("CHANNEL", "", @networkConf);
         }

      } else {
#         @networkConf = &change_line("ESSID", "", @networkConf);
#         @networkConf = &change_line("KEY", "", @networkConf);
#         @networkConf = &change_line("KEY1", "", @networkConf);
#         @networkConf = &change_line("KEY2", "", @networkConf);
#         @networkConf = &change_line("NICKNAME", "", @networkConf);
#         @networkConf = &change_line("NWID", "", @networkConf);
#         @networkConf = &change_line("FREQ", "", @networkConf);
      }
      &conf_write("/etc/sysconfig/network-scripts/ifcfg-$1", @networkConf);

      # update the page with new info
      &write_page($select);

#      $scr->at($status_line,0);
#      $scr->clreol();
#      $scr->puts("Done. Press any key to continue...");
#      &info_message($scr, "Configured device: $1 (/etc/sysconfig/network-scripts/ifcfg-$1)", 2);
      $scr->at($status_line,0);
      $restart_net = '1';
   } elsif ( $curr_entry eq 'DNS' ) {
      $scr->at($status_line,0);
      $scr->clreol();
      $scr->puts("Domain name server: ");
      $nameserver = &get_str($scr,$status_line,20,'0-9.', &readDNS());
      &writeDNS("$nameserver");
#      $scr->at($status_line,0);
#      $scr->clreol();
#      $scr->puts("Done. Press any key to continue...");
#      &info_message($scr, "Updated the primary DNS server (/etc/resolve.conf)", 2);
      $scr->at($status_line,0);
      $restart_net = '1';
   } elsif ( $curr_entry eq 'Hostname' ) {
      $scr->at($status_line,0);
      $scr->clreol();
      $scr->puts("Hostname: ");
      $hostname = &get_str($scr,$status_line,10,'a-z0-9.-_', $hostname);
      @networkConf = &conf_array("/etc/sysconfig/network");
      @networkConf = &change_line("HOSTNAME", "$hostname", @networkConf);
      &conf_write("/etc/sysconfig/network", @networkConf);
#      $scr->at($status_line,0);
#      $scr->clreol();
#      $scr->puts("Done. Press any key to continue...");
#      &info_message($scr, "Updated the system's hostname (/etc/sysconfig/network)", 2);
      $scr->at($status_line,0);
      $restart_net = '1';
   } elsif ( $curr_entry eq 'Gateway' ) {
      $scr->at($status_line,0);
      $scr->clreol();
      $scr->puts("Gateway: ");
      $gateway = &get_str($scr,$status_line,9,'0-9.', $gateway);
      @networkConf = &conf_array("/etc/sysconfig/network");
      @networkConf = &change_line("GATEWAY", "$gateway", @networkConf);
      &conf_write("/etc/sysconfig/network", @networkConf);
#      $scr->at($status_line,0);
#      $scr->clreol();
#      $scr->puts("Done. Press any key to continue...");
#      &info_message($scr, "Updated the default router (/etc/sysconfig/network)", 2);
      $scr->at($status_line,0);
      $restart_net = '1';
   }
#   $scr->getch();
}

$select = 3;
while(1){
   $total = &write_page($select);
   $key = $scr->getch();
#   &info_message($scr, undef);
   if ( $key =~ /kd/ or $key =~ /       / ) {
      if ( $total == $select ) {
#         $select = 3;
      } else {
         $select++;
      }
   } elsif ( $key eq 'ku' ) {
      if ( $select == 3 ) {
#         $select = $total;
      } else {
         $select--;
      }
   } elsif ( $key eq '
' or $key eq 'kr' or $key eq ' ' ) {
      &mod_entry();
   } elsif ( $key eq 'd' or $key eq 'q' or $key eq 'kl' or $key eq '' ) {
      last;
   } else {
   }
}

if ( $restart_net ) {
   while (1) {
      $scr->at($line+1,0);
      $scr->clreol();
      if ( $init ) {
         $key = 'y';
      } else {
         $scr->puts("Do you want to restart networking? [y/n]: ");
         $key = $scr->getch();
      }
      if ( $key eq 'y' ) {
         last;
      } elsif ( $key eq 'n' ) {
         $restart_net = ();
         last;
      }
   }
}

$scr->cooked();
$scr->at($line+1,0);
&info_message($scr, undef);

print "\n";

if ( $restart_net ) {
   system("/sbin/service network stop >/dev/null 2>&1");
   system("/sbin/service network start");
}
