#!/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:
      sidekick-systemroles is nifty.

   Options:
    -p, --prompt    Prompt for confirmation before installing packages
    -n, --noinittab Don't update inittab (even if it is necessary)
        --init      Run for the first time including defaults
    -h, --help      Show this help screen

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


GetOptions(
   'help|h'  => \$help,
   'prompt|p' => \$prompt,
   'noinittab|n' => \$noinittab,
   'init' => \$init,
);

if ( $help ) {
   die $usage;
}

if ( $init ) {
   $info_def = "Selected by default";
   $sel_default = '1';
}


my %roles = (
 "Default" =>           {
                           order       => "1",
                           groups      => "core base network",
                           default     => "1",
                           status      => "$info_def",
                           desc        => "Provides general system base level functionality"
                        },
 "Minimal X Environment" =>  {
                           order       => "2",
                           groups      => "core base x xfce",
                           default     => "1",
                           status      => "$info_def",
                           desc        => "Minimal desktop environment featuring XFCE",
                        },
 "Desktop:Gnome" =>     {
                           order       => "3",
                           groups      => "core base network x desktop gnome gnome_extras multimedia",
                           selected    => "",
                           desc        => "A full featured Gnome desktop environment",
                        },
 "Desktop:KDE" =>       {
                           order       => "4",
                           groups      => "core base network x desktop kde multimedia",
                           selected    => "",
                           desc        => "A full featured KDE desktop environment",
                        },
 "Desktop:XFCE" =>      {
                           order       => "5",
                           groups      => "core base network x desktop xfce multimedia",
                           selected    => "",
                           desc        => "A fast and lightweight desktop environment",
                        },
 "Desktop:Enlightenment" => {
                           order       => "6",
                           groups      => "core base network x desktop enlightenment multimedia",
                           selected    => "",
                           desc        => "The enlightened desktop environment",
                        },
 "Development" =>       {
                           order       => "7",
                           groups      => "core base devel xdevel",
                           selected    => "",
                           desc        => "Compilers, headers, and development tools",
                        },
 "Scientific" =>        {
                           order       => "8",
                           groups      => "core base devel xdevel scientific",
                           selected    => "",
                           desc        => "Development system including scientific apps",
                        },
 "Server Environment" => {
                           order       => "9",
                           groups      => "core base network server",
                           selected    => "",
                           desc        => "Base server environment (does not include services!)",
                        },
 "LAMP" =>              {
                           order       => "10",
                           groups      => "core base network server lamp",
                           selected    => "",
                           desc        => "Linux, Apache, MySQL and PHP/Mod_perl",
                        },
 "C-CLAMP" =>           {
                           order       => "11",
                           groups      => "core base network server lamp clustering",
                           selected    => "",
                           desc        => "Clustered cAos: Linux, Apache, MySQL and PHP/Mod_perl",
                        },
 "HPC Clustering" =>    {
                           order       => "12",
                           groups      => "core base network scientific clustering devel",
                           selected    => "",
                           desc        => "High Performance Computing/Clustering tools and utils",
                        },
);


sub role_sort {
   $roles{$a}{order} <=> $roles{$b}{order};
}

print "Obtaining current group list...";
$yum = &find_yum();
open(GROUPLIST, "$yum grouplist |");
while (<GROUPLIST>) {
   chomp;
   if ( $_ =~ /^Installed Groups:$/ ) {
      $installedgroup = '1';
      $yum_ok = '1';
   } elsif ( $_ =~ /^Available Groups:$/ ) {
      $installedgroup = ();
      $yum_ok = '1';
   } elsif ( $installedgroup ) {
      if ( $_ =~ /^\s+(\S+)$/ ) {
         $InstalledGroups{$1} = '1';
      } else {
         $availGroups = ();
      }
   }
}

if ( ! $yum_ok ) {
   warn "ERROR: Could not reach the configured mirror!\n";
   warn "       Check the network configuration or package repository settings.\n";
   sleep 2;
   die;
}


foreach $key ( keys %roles ) {
   $roles{$key}{installed} = '1';
   $roles{$key}{selected} = 'X';
   $roles{$key}{status} = 'Currently Installed';
   foreach $group ( split(/[,|\s]+/, $roles{$key}{groups})) {
      if ( $roles{$key}{default} and $init ) {
         $roles{$key}{status} = $info_def;
         $roles{$key}{selected} = 'I';
         $roles{$key}{install} = $roles{$key}{groups};
      } elsif ( ! $InstalledGroups{$group} ) {
         $roles{$key}{installed} = ();
         $roles{$key}{selected} = ();
         $roles{$key}{status} = "Not Installed";
      }
   }
}

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

sub write_page {
   $scr->at(0,0);
   $scr->on_blue();
   $scr->white();
   $scr->puts("cAos Linux: System role(s) and package group selection                          ");
   $scr->normal();

   my ( $sel, @NULL) = @_;
   $line = 2;
   $count = 1;
   $scr->at($line,1);
   $scr->bold();
   $out=sprintf("%3.3s %-21.21s %-52.52s", 
         "Sel",
         "Role",
         "Description");
   $scr->puts($out);
   $scr->normal();
   $line++;
   $count++;

   @role_names = ();
   foreach ( sort role_sort keys %roles ) {
      $scr->at($line,1);
      if ( $sel == $line ) {
         $scr->reverse();
         $scr->cyan();
         $scr->inverse();
         $selected_desc = $roles{$_}{status};
         $selected_desc_level = $roles{$_}{statuslevel};
      } elsif ( $roles{$_}{selected} eq 'I' ) {
         $scr->bold();
         $scr->green();
      } elsif ( $roles{$_}{selected} eq 'R' ) {
         $scr->bold();
         $scr->red();
      } else {
         $scr->normal();
      }
      $out=sprintf("[%1.1s] %-21.21s %-52.52s", 
            $roles{$_}{selected}, $_, $roles{$_}{desc});
      $scr->puts($out);
      $line++;
      $count++;
      push(@role_names, $_);
      $scr->normal();
   }
   $info_done_line = sprintf("Status: %-67.67s", $selected_desc);
   &info_message($scr, "$info_done_line", $selected_desc_level);
   $scr->at(21,0);
   $scr->clreol();
   $scr->cyan();
   $scr->puts("Arrow keys to navigate, space/enter to select, 'd' when done, [ESC] to quit: ");
   $scr->normal();
   return($count);
}

$select = 3;
while(1){
   $total = &write_page($select);
   $key = $scr->getch();
   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 ' ' or $key eq 'kr' ) {
      $n = $role_names[$select-3];
      if ( $roles{$n}{selected} eq 'X' or $roles{$n}{selected} eq 'I' ) {
         $roles{$n}{install} = ();
         if ( $roles{$n}{installed} ) {
            $roles{$n}{status} = "Selected for removal";
            $roles{$n}{statuslevel} = "2";
            $roles{$n}{remove} = "1";
            $roles{$n}{selected} = "R";
         } else {
            $roles{$n}{status} = "Not Installed";
            $roles{$n}{statuslevel} = "0";
            $roles{$n}{selected} = ();
         }
      } else {
         if ( $roles{$n}{installed} ) {
            $roles{$n}{status} = "Currently Installed";
            $roles{$n}{statuslevel} = "0";
            if ( $roles{$n}{default} and $init ) {
               $roles{$n}{selected} = "I";
            } else {
               $roles{$n}{selected} = "X";
            }
            $roles{$n}{remove} = ();
         } else {
            $roles{$n}{status} = "Selected for installation";
            $roles{$n}{statuslevel} = "1";
            $roles{$n}{install} = $roles{$n}{groups};
            $roles{$n}{selected} = "I";
         }
      }
   } elsif ( $key eq 'd' ) {
      $inst = '1';
      last;
   } elsif ( $key eq 'q' or $key eq 'kl' or $key eq '' ) {
      last;
   } else {
   }
}

$scr->normal();
&info_message($scr, undef);
$scr->cooked();
$scr=();

print "\n";

if ( $inst ) {
   foreach $key ( keys %roles ) {
      if ( $roles{$key}{selected} eq 'X' ) {
         foreach $group ( split(/[,|\s]+/, $roles{$key}{groups})) {
            $selected{$group} = '1';
         }
      }
      if ( $roles{$key}{selected} eq 'I' ) {
         foreach $group ( split(/[,|\s]+/, $roles{$key}{groups})) {
            $install{$group} = '1';
         }
      }
   }
   foreach $key ( keys %roles ) {
      if ( $roles{$key}{remove} ) {
         foreach $group ( split(/[,|\s]+/, $roles{$key}{groups})) {
            if ( ! $install{$group} and ! $selected{$group} ) {
               $remove{$group} = '1';
            } else {
               $skipping{$group} = '1';
            }
         }
      }
   }
   if ( %skipping ) {
       foreach $skip (keys %skipping) {
          $skippy .= " " if $skippy;
          $skippy .= $skip;
       }
       warn "Other selections depend on the following groups:\n";
       warn "   [$skippy]\n";
       warn "Thus they have been skipped.\n";
   }

   $init = '3';

   foreach $group ( keys %install ) {
      $install_groups .= "$group ";
      if ( $group eq "x" ) {
         $init = '5';
      }
   }
   foreach $group ( keys %remove ) {
      $remove_groups .= "$group ";
   }

   if ( $remove_groups ) {
      print "\n# $yum -t groupremove $remove_groups\n\n";
      system("$yum -t groupremove $remove_groups");
   }

   if ( $? != 0 ) {
      print "\nPress [ENTER] to continue...";
      $foo = <STDIN>;
   }

   if ( $install_groups ) {
      if ( $prompt ) {
         print "\n# $yum -t groupinstall $install_groups\n\n";
         system("$yum -t groupinstall $install_groups");
      } else {
         print "\n# $yum -ty groupinstall $install_groups\n\n";
         system("$yum -ty groupinstall $install_groups");
      }
   }

   if ( $? != 0 ) {
      print "\nPress [ENTER] to continue...";
      $foo = <STDIN>;
   }

   if ( $? == '0' and ! $noinittab ) {
      open(INITTAB, "< /etc/inittab");
      while(<INITTAB>) {
         chomp;
         if ( $_ =~ /^id:(\d):initdefault:$/ ) {
            if ( $1 != $init ) {
               $update_inittab = '1';
            } else {
               $update_inittab = ();
            }
            $inittab .= "id:$init:initdefault:\n";
         } else {
            $inittab .= "$_\n";
         }
      }
      close INITTAB;
      if ( $update_inittab ) {
         if ( $init == '5' ) {
            print "\nConfiguring system to boot into GUI mode\n";
            open(INITTAB, "> /etc/inittab");
            print INITTAB $inittab;
            close INITTAB;
         } else {
#            print "\nConfiguring system to boot into TEXT mode\n";
         }
      }
   }
}


