#!/usr/bin/env perl
use warnings;
use diagnostics;

use strict;
use FindBin;
use lib "./lib";
use lib $FindBin::RealBin;
use HotSaNICparser;
use HotSaNICshellio;
use Cwd;

$|=1;

my $ALLYES;

my $THISDIR=Cwd::cwd();
my $args=lc join "",@ARGV;

if ( index($args,"y") >=0 ) { $ALLYES="y"; } else { $ALLYES=""; }
if ( index($args,"?") >=0 ) { 
  print "Usage:
  
  setup.pl [m[y]][s][g][?]

  when run without switches, the default value of \"msg\" will be used.
  
  m    configure modules individually

  y    (in combination with \"m\")
       configure all modules
       automatically answers \"Yes\" when asked if module shall be
       used or displayed. This has nothing to do with the modules'
       own configuration, it just affects the main setup behaviour.

  s    generate main settings
    note: if you want to add or remove modules using the \"m\" switch,
          the \"s\" switch has also to be set to modify the main
	  settings accordingly.  In this case the \"y\" swich will
	  automatically activate all available modules!
  
  g    generate \"rrdgraph\" start/stop scipt
  
  ?    display this help text.\n\n";
  exit;
  }

if ( (index ($args,"g")<0) && (index ($args,"s")<0) && (index ($args,"m")<0) )  { $args=$args."gsm"; }

my $RUN="";
my $SHOW="";

if ( ! -e "var" ) { mkdir "var",0755; }
if ( ! -e "var/settings" ) { mkdir "var/settings",0755; }
if ( ! -e "var/log" ) { mkdir "var/log",0755; }
if ( ! -e "var/run" ) { mkdir "var/run",0755; }
if ( ! -e "var/modules" ) { mkdir "var/modules",0755; }

if ( index($args,"m") >=0 ) { configure_modules(); }
if ( index($args,"s") >=0 ) { configure_main(); }
if ( index($args,"g") >=0 ) { write_rrdgraph_script(); }

if ( -e "settings.new" ) {
  HotSaNICparser::backup_file("settings");
  system "mv -f settings.new settings";
  }
system "ln -sf ../../settings var/settings/main";

# build array with all settings files in the "modules" dir
#
my @allsettings;
require File::Find;
$File::Find::name="";  # suppress stupid warning...
File::Find::find( {wanted => sub { /^settings\z/s && push @allsettings,$File::Find::name; } }, 'modules');

for my $item (@allsettings) {
  chomp $item;
  my $name;
  ($name=$item) =~ s/ules\/(.*)\/.*/_$1/g;
  system "ln -sf ../../$item var/settings/$name\n";
  }

print "\nNow adapt all settings files to satisfy your needs.\nThey are all linked to the directory  <HotSaNIC_installdir>/var/settings .\n\n";
exit 0;



sub write_rrdgraph_script {

  print "\nWriting start/stop script \"rrdgraph\" ...";

  open OUT,">rrdgraph";
  if ( -e "/bin/bash" ) { print OUT "#!/bin/bash\n"; } else { print OUT "#!/usr/bin/env sh\n"; }
  print OUT "# chkconfig: 12345 55 45
# description:  System statistics

cd \"$THISDIR\"

. ./settings

case \$1 in
  start)
    echo \"Starting rrdtimer...\"
    ./rrdtimer.pl Dp
    ;;
  stop)
    echo \"Stopping rrdtimer...\"
    if [ -e \"\$PIDFILE\" ]; then 
      PID=`cat \"\$PIDFILE\"`
      for nn in \$PID ; do kill \$nn; done
    else
      echo \"pid-file not found, rrdtimer not running?!\"
      fi
    ./clearall CLEAR_COUNTERS
    ;;
  status)
    if [ -e \$PIDFILE ]; then
      echo \"main process on PID \`cat \$PIDFILE\` (according to PID-file)\"
    else
      echo \"pid-file not found, rrdtimer not running?!\"
      fi
    ;;
  restart)
    ./rrdgraph stop
    ./rrdgraph start
    ;;
  *)
    echo \"usage: rrdgraph [start|stop|status|restart]\"
    ;;
  esac
";
  close OUT;
  chmod 0755,"rrdgraph";

  print" Ok.\n";
  }


sub configure_modules {

  print "Configuring modules:\n";
  
  my @mods=HotSaNICparser::scan_for_modules( "./modules", 0, "*" );
  my @run;
  my @show;
  foreach my $dir (@mods) {
    if ( ($dir eq ".") || ($dir eq "..") || ($dir eq "CVS") ) { next; }
    my $modname=uc $dir;
    my $input=$ALLYES;
    if ($input eq "") {
      print "\n\nModule found: $modname\n\nDescription:\n";
      if ( -e "modules/$dir/.description") {
        open FILE,"modules/$dir/.description";
        while (<FILE>) { print "   $_"; }
        close FILE;
        }
      else { print "(not available)"; }
      $input=HotSaNICshellio::askyesno("Do you want to use this module","y");
      }
  
    if ($input eq "y") {
      push @run,lc $modname;
      $input=$ALLYES;
      if ($input eq "") {
        $input=HotSaNICshellio::askyesno("Do you want to show this module's graphs on the webpage","y");
	}
      if ($input eq "y") { push @show,lc $modname; }
      }
    print "\n----------------------------------------\n";
    }
  foreach my $dir (@run) {
    print "\nsetting up $dir ...\n";
    if (-e "modules/$dir/setup.pl") { system "cd modules/$dir; ./setup.pl; cd .."; }
    else { system "cd modules/$dir; ./setup; cd .."; }
    }
  $RUN=join " ",@run;
  $SHOW=join " ",@show;
  print" Ok.\n";
  }



sub configure_main {

  print "Writing main settings ...\n";

  my $convertpath;
  my %VARS;

  my $file=".settings.default";
  my $newfile="settings";
  if ( -e "settings" ) {
    $newfile="settings.new";
    my @CONF=HotSaNICparser::read_settings(".");
    foreach (@CONF) {
      my ($var,$val)=HotSaNICparser::parse_line($_);
      $VARS{$var}=$val;
      }
    }
  open FILE,$file;
  open NEWFILE,">$newfile";

  while (<FILE>) {
    chomp;
    
    my ($var,$value,$comment)=HotSaNICparser::parse_line($_);

    if (defined $VARS{$var}) { $value=$VARS{$var}; }
    if ($var eq "RUN") { if ($RUN ne "") { ($value=$RUN) =~ s/^ *//; } }
    if ($var eq "SHOW") { if ($SHOW ne "") { ($value=$SHOW) =~ s/^ *//; } }

    if ( ($value eq "" ) || (lc $value eq "not configured") ) {

      if ($var eq "DAEMONDIR") {
        print "  checking path to \"rrdtimer.pl\" (current: '$value')\n";
        if ( -e "$THISDIR/rrdtimer.pl" ) { $value=$THISDIR; }
        }

      if ($var eq "BINPATH") {
        print "  checking path to \"rrdtool\" (current: '$value')\n";
        my @found=HotSaNICparser::locate_files("bin\/rrdtool");
        if (@found) {
          foreach my $nn (@found) { $nn=~ s/\/rrdtool$//g; }
          $value=HotSaNICshellio::choose($value,"rrdtool could not be found. If you already installed it, please edit the settings file.",@found);
          }
        }

      if ($var eq "CONVERTMETHOD") {
        print "  guessing convert method...\n";
        print "  checking for Image::Magick perl module...";
	eval {
          require Image::Magick;
	  };
	if ( $@ ) { 
          print " not found\n";
          }
        else {
          print " found\n";
          $value="I::M";
          }

        print "  checking path to \"convert\" from ImageMagick (current: '$value')\n";
        my @found=HotSaNICparser::locate_files("bin\/convert|grep convert\$");
        if (@found) {
          $convertpath=HotSaNICshellio::choose($value,"convert could not be found. If ImageMagick package is already installed, please edit the settings file.",@found);
          $value="ImgMgck" if ( $value ne "I::M" );
          }
        $value="HTML" if ( $value eq "not configured" );
        }

      if ($var eq "CONVERTPATH") {
         $value=$convertpath;
        }

      if ($var eq "SNMPWALK") {
        print "  checking path to \"snmpwalk\" (current: '$value')\n";
        my @found=HotSaNICparser::locate_files("bin\/snmpwalk");
        if (@found) {
          $value=HotSaNICshellio::choose($value,"snmpwalk could not be found. If you already installed it, please edit the settings file.",@found);
          }
        }

      if ($var eq "SNMPGET") {
        print "  checking path to \"snmpget\" (current: '$value')\n";
        my @found=grep /snmpget$/,HotSaNICparser::locate_files("bin\/snmpget");
        if (@found) {
          $value=HotSaNICshellio::choose($value,"snmpget could not be found. If you already installed it, please edit the settings file.",@found);
          }
        }
      
      if ($var eq "SNMPBULKWALK") {
        print " checking path to \"snmpbulkwalk\" (current: '$value')\n";
	my @found=grep /snmpbulkwalk$/,HotSaNICparser::locate_files("bin\/snmpbulkwalk");
	if (@found) {
	  $value=HotSaNICshellio::choose($value,"snmpbulkwalk could not be found. If you already installed it, please edit the settings file.", @found);
	  }
        }
      }

    if ($var ne "") { print NEWFILE "$var=\"$value\""; print "$var=\"$value\"\n"; }
    if ($comment ne "") { $comment="" if $comment eq " "; print NEWFILE "#$comment"; }
    print NEWFILE "\n";
      
#     if ( ($value ne " ") && ($var !~ /^#/) ) { print "$var=\"$value\"\n"; }
#     } else { $var=""; }
#   if ($value ne " ") { print NEWFILE "$var=\"$value\"\n"; }
#   else { print NEWFILE $var,"\n"; }
    }
  close FILE;
  close NEWFILE;

  print"\n --- Main settings generated. ---\n";
  }

