#!/usr/bin/env perl

$|=1;

use lib "../../lib";
use HotSaNICparser;
use HotSaNICmod;

my $MODLOGDIR=".";
my $MODPIDFILE="running.pid";
my $MODNAME=HotSaNICparser::get_module_name();


checkargs(@ARGV);


######################################################################
#
# wrapper
#
sub sample {
  if (-e "./read-data") { system ("nice -5 ./read-data"); }
  elsif (-e "./read-data.pl") { system ("nice -5 ./read-data.pl"); }
  }

sub update {
  }

######################################################################
#
# fork into background
#
sub daemonize {
  my ($MODPIDFILE,$MODNAME,$MODLOGDIR)=@_;

# set signal handlers
#
  $SIG{TERM} = \&terminate;
  $SIG{HUP} = \&configure;
  $SIG{USR1} = \&sample;
  $SIG{USR2} = \&update;

  $MODLOGDIR="";
# open STDIN,"/dev/null";
# open STDOUT,">>$MODLOGDIR"."/mod_$MODNAME.log";
# open STDERR,">>$MODLOGDIR"."/mod_$MODNAME.log";
# chdir "/";
  fork && exit 0;
  }


######################################################################
#
# terminate module daemon
#
sub terminate {
  HotSaNICmod::dupe_control("stop",$MODNAME,"");
  unlink $MODPIDFILE if -e $MODPIDFILE;
# close STDIN;
# close STDOUT;
# close STDERR;
  exit 0;
  }


######################################################################
#
# check cmdline arguments
#
sub checkargs {
  $args=join " ",@_;

  if ( $args eq "" ) {
    print "arguments missing!\n";
    print "usage: $0 [start/stop/status/version]\n";
    }

  if ( $args =~ /version/) {
    print "wrapper script\n";
    }
  
  if ( $args =~ /start/) {
    my ($pid,$uptime)=HotSaNICmod::dupe_control("check",$MODNAME,"");
    if ($pid > 0) { print "$MODNAME already running on PID $pid\n"; }
    else {
      daemonize($MODPIDFILE,$MODNAME,$MODLOGDIR);
      HotSaNICmod::dupe_control("start",$MODNAME,"");
      while (1 == 1) { sleep; }
      }
    }

  if ( $args =~ /status/) {
    my ($pid,$uptime)=HotSaNICmod::dupe_control("check",$MODNAME,"");
    print "$MODNAME running on PID $pid for $uptime sec.\n";
    }

  if ( $args =~ /sample/) {
    my ($pid,$uptime)=HotSaNICmod::dupe_control("check",$MODNAME,"");
    if ($pid > 0) { kill "SIGUSR1",$pid; }
    else { print "no process running.\n"; }
    }

  if ( $args =~ /stop/) {
    my ($pid,$uptime)=HotSaNICmod::dupe_control("check",$MODNAME,"");
    if ($pid > 0) { kill "SIGTERM",$pid; }
    else { print "no process running.\n"; }
    }
  }

