#! /usr/bin/perl

use strict ;
use warnings ;

my $prog = substr $0, rindex ( $0, '/' ) + 1 ;
my $Usage = <<USAGE ;
Usage: $prog [-v] [-q] [-d] dist arg ...
option v : be verbose
option q : be quiet
option d : show debug info
USAGE
sub Usage { die "$_[0]$Usage" ; }
sub Error { die "[error] $prog: $_[0]\n" ; }
sub Warn  { warn "[warn] $prog: $_[0]\n" ; }

# usage: &GetOptions(ARG,ARG,..) defines $opt_ID as 1 or user spec'ed value
# usage: &GetOptions(\%opt,ARG,ARG,..) defines $opt{ID} as 1 or user value
# ARG = 'ID' | 'ID=SPC' | 'ID:SPC' for no-arg, required-arg or optional-arg
# ID  = perl identifier
# SPC = i|f|s for integer, fixedpoint real or string argument

use Getopt::Long ;
Getopt::Long::config ( 'no_ignore_case' ) ;
my %opt = () ; Usage '' unless GetOptions
  ( \%opt, qw(v q d f) ) ;
Usage("Arg count\n") if @ARGV < 2 ;

my $DIST = shift ;
my @ARGS = @ARGV ;

my $SYSC = '/usr/bin/systemctl' ;

my ( $cmd, @args ) ;

if ( $DIST eq 'ubuntu' )
  { @args = ( grep { -f "/etc/init/$_.conf" } @ARGS ) [ 0 ] ;
    if ( @args ) { $cmd = 'service' ; push @args, 'status' }
  }

unless ( $cmd )
  { $cmd = ( grep { -f $_ } map { "/etc/init.d/$_" } @ARGS) [ 0 ] ;
    @args = qw(status) ;
  }

if ( ! $cmd and -f $SYSC )
  { my $hav ;
    for my $arg ( @ARGS )
      { if ( 0 == _get_out ( $SYSC, 'is-enabled', $arg ) -> xit )
          { $hav = $arg ; last ; }
      }
    if ( $hav ) { $cmd = $SYSC ; @args = ( 'is-active', $hav ) ; }
  }

OBB::TT ( '  dist %s prog %s args %s', $DIST, $cmd, "@args" ) ;

if ( $cmd and @args )
  { my $out = _get_out $cmd, @args ;
    my $val = $out -> xit ? Dmon::SPIN_DO : Dmon::SPIN_UP ;
    my $nam = $item -> name ;
    $item -> set_val ( $val ) ;
  }
else
  { $item -> perr ( "no init[.d] file [@ARGS]" ) ; }

