#------------------------------------------------------------------#
#-- Main Actions --------------------------------------------------#
#-- Calling any of these actions is controlled by the main routine #
#-- None of these Actions returns control to the main routine      #
#-- unless there is an error.                                      #
#------------------------------------------------------------------#

#------------------------------------------------------------------#
# Handles the Preferences Page
#------------------------------------------------------------------#
sub PREF {
    my($type) = $in{s} || 'edit';
    &DEBUG("type = $type");
    require "$Libdir/prefs.pl";
    &Prefs(lc($type));
}

#------------------------------------------------------------------#
# Handles the Setup Page.
# Valid sub-actions are: discover and lookup
#------------------------------------------------------------------#
sub SETUP {
    &DEBUG("in{s} = ",$in{s});
    require "$Libdir/editor.pl";
    &{uc($in{s})} if $in{s} =~ /discover|lookup/i;
    &EDITOR();
}

#------------------------------------------------------------------#
# Handles the "Recheck" button (Admin only)
# This spawns an additional autocheck process independent of any
# currently running autocheck. The DISPLAY routine is not called
# until the autocheck is complete or is in error
#------------------------------------------------------------------#
sub RECHECK {
    #&Error('Recheck capability is not available in DEMO mode.') if $DEMO;
    &StartAutoCheck($Autorecheck.' auto'.$$.'.pid -1') if $AdminUser;
    &DISPLAY();
}

#------------------------------------------------------------------#
# Handles all calls to the Detail Page
# Valid sub-actions are:
#   traceroute quickport fullport history updateinfo
#   usercmds recheckos runscript overview portconfig
# Any other sub-action is ignored and the overview page is displayed
#------------------------------------------------------------------#
sub DETAIL {
    $in{s} ||= 'overview';    &DEBUG("in{s} = ",$in{s});
    require "$Libdir/detail.pl";
    &ReadServices();
    my $result = &{uc($in{s})} if $in{s} =~ /traceroute|quickport|fullport|history|updateinfo|usercmds|recheckos|runscript|overview|portconfig/i;
    &DisplayDETAIL($in{site}, $result);
}

#------------------------------------------------------------------#
# Handles all Script calls and then displays the results on the
# Detail page
#------------------------------------------------------------------#
sub SAPI {
    &DEBUG("in{site,port,script,timeout} = ",join(", ",$in{site},$in{port},$in{script},$in{timeout}));
    
    require "$Libdir/sapi.pl";
    my ($ok, $result) = &sapi($in{site},$in{port},$in{script},$in{timeout});
    &Error($result) unless $ok;

    require "$Libdir/detail.pl";
    &ReadServices();
    &DisplayDETAIL($in{site},$result);
}

#------------------------------------------------------------------#
# Handles the Script definition page
#------------------------------------------------------------------#
sub SCRIPT {
    require "$Libdir/prefs.pl";
    &ScriptPage() if ($in{edit} or $in{save} or $in{delete});
    $in{section} = 'SCRIPTS';
    &Prefs();
}

#------------------------------------------------------------------#
# Handles the autocheck button
#------------------------------------------------------------------#
sub AUTO {
    #&Error('Auto Check mode is not available in DEMO mode.') if $DEMO;
    my($enabled);

    &DEBUG("in{s} = ",$in{s});
    if ($in{s} =~ /on/i) {
      $enabled      = 'enabled';
      $Autointerval = abs($Autointerval);
    } elsif ($in{s} =~ /off/i) {
      &StopAutoCheck();
      $enabled      = 'disabled';
      $Autointerval = -abs($Autointerval);
    }

    undef %in;
    $in{a} = 'pref';
    $in{Autointerval} = $Autointerval;
    require "$Libdir/prefs.pl";
    &Prefs('save',1);
    $in{f} ||= 'default_basic';
    &DEBUG('Auto Check has been ',$enabled);
    &DISPLAY('Auto Check has been '.$enabled);
}

#------------------------------------------------------------------#
# Handles the default action
#------------------------------------------------------------------#
sub DISPLAY {
    my $extra      = shift;
    my $htmlstats  = "";
    my $haveconfig = -f $Configfile;
    my $autolock   = -f $Vardir."/autorecheck.lock";
    my $firstcheck = '<small>(The first check might take a few minutes as it discovers your network and each device\'s operating system.)</small>';

    require "$Libdir/gendisp.pl";
    &DEBUG('starting');
    
    &FILTER() if $in{f} eq 'filter_new_filter';  #Catch new filter request

    if ($in{s} eq 'cleareventlog') {
      &ClearEventLog() if $AdminUser;
      $in{s} = '';
    }

    if ($in{f}) {
        unless ($haveconfig) {
          print &Header($Myname,'',0);
          print <<HTML;
            <h1>nPulse Message</h1>
            <p>If you are viewing this page from nPulse then you have either not yet entered valid 
            <b>Setup</b> information</a> or <b>Autocheck</b> has not finished it's first scan or 
            (if you have disabled the automatic checking) you have not yet clicked on the manual 
            Recheck button.</p><p>For more information see the <a href="$Help_url">Help Page</a>.</p>
HTML
          print &Footer();
          exit;
        }
        print &Header($Myname,$extra,1),&CREATE(),&Footer();

    } elsif ($in{s}) {
      print &DisplayHTMLfile((($in{s} =~ /help/i)      ? $Helpfile :
                              ($in{s} =~ /copyright/i) ? $Copyrightfile : ''),$extra);
      
    } else {
      print &Header($Myname,$extra,0);
      $htmlstats = &AdminHeaderInfo() if $haveconfig;
      if ($AdminUser) {
        local($/) = undef;
        open(W, "<$AdminWelcome") or &Error("Unable to locate $AdminWelcome");
        eval (<W>);  close(W);
      } else {
        local($/) = undef;
        open(W, "<$UserWelcome") or &Error("Unable to locate $UserWelcome");
        eval (<W>);  close(W);
      }
      print <<HTML;
        <hr><p>The most recent versions of <b>nPulse</b> are available at
        <a href="http://freshmeat.net/projects/npulse/">http://freshmeat.net/projects/npulse/</a> or
        <a href="http://www.horsburgh.com/h_npulse.html">http://www.horsburgh.com/h_npulse.html</a></p>
        <p><small>All company logos and names are copyrighted or trademarked by their respective companies.</small></p>
HTML
      print &Footer();
    }
    &WriteKookie();
    exit;
}

#------------------------------------------------------------------#
# Handles the "Status" button
#------------------------------------------------------------------#
sub STATUS {
  my $servstat = &ServerCheckStatus();
  my $autostat = &AutoCheckStatus();
  
  my($numhosts,$numports,@ports);
  $numhosts = $numports = 0;
  foreach $ip (keys %Config) {
    $numhosts++;
    @ports = split(/,/,$Config{$ip}{portlist});
    $numports += $#ports+1;
  }

  if ($servstat) {
    my($auto,$nauto,$autocheck);
    if ($autostat) { $auto = 'Stop Process';  $nauto = 'off'; }
    else           { $auto = 'Start Process'; $nauto = 'on'; }

    print &Header($Myname,'nPulse Status',2),
          '<blockquote><span style="',$Fsn,'">',scalar(localtime(time)),'<p>',
          'The Web Server is <font color="#',
          ($servstat?'00cc00">Running':'cc0000">Stopped'),'</font><p>',
          'The Automatic Network Monitor is <font color="#',
          ($autostat?'00cc00">'.((-f $Vardir.'/autorecheck.lock')?
          'Currently scanning the network':'Sleeping'):'cc0000">Stopped'),'</font> [',
          '<a href="',$nPulseurl,'?a=auto&s=',$nauto,'">',$auto,'</a>]<p>',
          'nPulse is monitoring ',$numhosts,' hosts and a total of ',$numports,' ports</span>',
          '<form method="post" action="',$nPulseurl,'"><input type="hidden" name="a" value="status">',
          '<input type="hidden" name="pinghosts" value="1"><table border=0><tr><td>Perform a PING sweep on</td>',
          '<td nowrap><input type="text" name="ipmask" size="18" style="',$Fss,'"> ',
          '<input type="submit" style="',$Fss,'" value="Go"></td></tr>',
          '<tr><td></td><td nowrap><span style="',$Fxs,'">(leave blank to use current ip addresses)</span></td></tr></table></form>',
          ($in{pinghosts}?&PingHosts($in{ipmask}):''),
          '<form method="post" action="',$nPulseurl,'"><input type=hidden name=a value="status">',
          '<input type="hidden" name="portsweep" value="1"><table border=0><tr><td>Perform a PORT sweep on</td>',
          '<td nowrap><span style="',$Fss,'"><input type="text" name="ipmask" size="18" style="',$Fss,
          '"> Port:<input type="text" name="port" size="5" style="',$Fss,'"> ',
          '<input type="submit" style="',$Fss,'" value="Go"></span></td></tr>',
          '<tr><td></td><td nowrap><span style="',$Fxs,'">(leave blank to use current ip addresses)</span></td></tr></table></form>',
          ($in{portsweep}?&PortSweep($in{ipmask},$in{port}):''),
          '</blockquote>';
  } else {
    print scalar(localtime(time)),"\n",
          'The Web Server is ',($servstat?'Running':'Stopped'),"\n",
          'The Automatic Network Monitor is ',
          ($autostat?((-f $Vardir.'/autorecheck.lock')?
          'Currently scanning the network':'Sleeping'):'Stopped'),"\n",
          'nPulse is monitoring ',int($numhosts),' hosts and a total of ',int($numports),' ports>',"\n";
  }

#  if ($ADEBUG) {
#    print "<small><pre>Config Hash\n";
#    foreach $ip ( sort keys %Config ) {
#      print $ip,":\n";
#      foreach $k ( sort keys %{$Config{$ip}} ) {
#        print "  $k => $Config{$ip}{$k}\n";
#      }
#    }
#    print "</pre></small>";
#  }

  print &Footer();
  exit;
}

#------------------------------------------------------------------#
# Handles the FILTER action
# Strictly speaking, this routine is not an action, it is called
# by the DISPLAY routine
#------------------------------------------------------------------#
sub FILTER {

  require "$Libdir/filter.pl";
  my $fname = $in{fname};
  my $style = $in{style};
  if ($in{efname}) {
    ($fname,$style) = $in{efname} =~ /^(.*)_(.*)$/;
    $in{fname} = $fname;
    $in{style} = $style;
  }
  &Error("Invalid filter name: $fname") if $fname =~ /[^A-Za-z0-9_]/;
  &Error('You cannot modify or delete the default filter.') if $fname eq 'default';

  if ($in{delete}) {
    &Error('You must specify a filter name.') unless $fname;
    &Error('You must specify a filter style.') unless $style;
    &DeleteFilter($fname,$style);
    $in{a} = 'display';
    $in{f} = 'default_basic' if $in{f} eq $fname.'_'.$style;
    &DISPLAY();
  
  } elsif ($in{save}) {
    &Error('You must specify a filter name.') unless $fname;
    &Error('You must specify a filter style.') unless $style;
    &Error('You must specify at least one address.') unless $in{filter};
    &SaveFilter($fname,$style,$in{filter});
    $in{a} = 'display';
    $in{f} = $fname.'_'.$style;
    &DISPLAY();
  
  } elsif ($in{'edit'}) {
    &Error('You must specify a filter name.') unless $fname;
    &Error("Unable to locate filter: $fname ($style)") unless defined $Filters{$fname}{$style};
    &FilterPage($fname,$style);
  
  } else {
    &FilterPage();
  }
  exit;
}

1;
