#!/bin/bash
# vim: expandtab:ts=4:sw=4:syntax=perl

# read rc files if exist
unset PROFILEDOTD
[ -e /etc/thruk/thruk.env  ] && . /etc/thruk/thruk.env
[ -e ~/etc/thruk/thruk.env ] && . ~/etc/thruk/thruk.env
[ -e ~/.thruk              ] && . ~/.thruk
[ -e ~/.profile            ] && . ~/.profile

BASEDIR=$(dirname $0)/..

# git version
if [ -d $BASEDIR/.git -a -e $BASEDIR/lib/Thruk.pm ]; then
  export PERL5LIB="$BASEDIR/lib:$PERL5LIB";
  if [ "$OMD_ROOT" != "" -a "$THRUK_CONFIG" = "" ]; then export THRUK_CONFIG="$OMD_ROOT/etc/thruk"; fi
  if [ "$THRUK_CONFIG" = "" ]; then export THRUK_CONFIG="$BASEDIR/"; fi

# omd
elif [ "$OMD_ROOT" != "" ]; then
  export PERL5LIB=$OMD_ROOT/share/thruk/lib:$PERL5LIB
  if [ "$THRUK_CONFIG" = "" ]; then export THRUK_CONFIG="$OMD_ROOT/etc/thruk"; fi

# pkg installation
else
  export PERL5LIB=$PERL5LIB:@DATADIR@/lib:@THRUKLIBS@;
  if [ "$THRUK_CONFIG" = "" ]; then export THRUK_CONFIG='@SYSCONFDIR@'; fi
fi

eval 'exec perl -x $0 ${1+"$@"} ;'
    if 0;
# / this slash makes vscode syntax highlighting work
#! -*- perl -*-
#line 35

###################################################
use warnings;
use strict;

BEGIN {
    for my $a (@ARGV) {
        if($a eq '-T') {
            $ENV{'THRUK_TIMER'} = 1;
            last;
        }
    }
    use Thruk::Timer qw/timing_breakpoint/;
    &timing_breakpoint('./script/thruk');
};
use Getopt::Long ();

my $options = {
    'verbose'        => 0,
    'backends'       => [],
    'headers'        => [],
    'commandoptions' => [],
};
Getopt::Long::Configure('no_ignore_case');
Getopt::Long::Configure('bundling');
Getopt::Long::Configure('pass_through');
Getopt::Long::GetOptions(
   "h|help"             => \$options->{'help'},
   "v|verbose"          => sub { $ENV{'THRUK_VERBOSE_ARG_SET'}=1; $options->{'verbose'}++ },
   "T"                  => sub {  }, # already processed
   "q|quiet"            => \$options->{'quiet'},
   "V|version"          => \$options->{'version'},
     "remote-url=s"     => \$options->{'remoteurl'},
   "k|insecure"         => \$options->{'insecure'},
   "H|header=s"         =>  $options->{'headers'},
     "local"            => \$options->{'local'},
   "c|credential=s"     => \$options->{'credential'},
   "b|backend=s"        =>  $options->{'backends'},
   "A|auth=s"           => \$options->{'auth'},
   "y|yes"              => \$options->{'yes'},
   "f|force"            => \$options->{'force'},

     "list-commands"    => \$options->{'listcommands'},
   "l|list-backends"    => \$options->{'listbackends'},
   "a|action=s"         => \$options->{'action'},
) or do {
    print "usage: $0 [<globaloptions>] <plugin> [<options>]\nsee --help for detailed help.\n";
    _print_modules();
    exit 3;
};
@{$options->{'commandoptions'}} = @ARGV;
if($options->{'help'}) {
    if($options->{'commandoptions'} && $options->{'commandoptions'}->[0]) {
        require Thruk::Utils::CLI;
        my $module = ucfirst($options->{'commandoptions'}->[0]);
        eval("require Thruk::Utils::CLI::".$module);
        my $out = Thruk::Utils::CLI::get_submodule_help($module);
        print STDERR $out->{'output'};
        exit($out->{'rc'});
    }
    require Pod::Usage;
    Pod::Usage::pod2usage( { -verbose => 2, -exit => 3 } );
    exit(3);
}
if($options->{'version'}) {
    require Thruk::Config;
    printf("thruk v%s%s\n",
        Thruk::Config::get_thruk_version(),
        ($Thruk::Config::GIT_HASH ? " (".$Thruk::Config::GIT_HASH.")" : ""),
    );
    exit 0;
}
if(!$options->{'action'} and scalar @{$options->{'commandoptions'}} == 0 and !$options->{'listbackends'} and !$options->{'listcommands'}) {
    print "usage: $0 [<globaloptions>] <plugin> [<options>]\nsee --help for detailed help.\n";
    _print_modules();
    exit 3;
}
if($options->{'listcommands'}) {
    _print_modules();
    exit 0;
}

# required when starting thruk as root to get logging right
$ENV{'THRUK_VERBOSE'}    = $ENV{'THRUK_VERBOSE'} // $options->{'verbose'} // 0;
$ENV{'THRUK_QUIET'}      = 1 if $options->{'quiet'};
$ENV{'THRUK_VERBOSE'}    = 0 if$ENV{'THRUK_QUIET'};
$ENV{'THRUK_MODE'}       = 'CLI_SETUID';
$ENV{'MONITORING_LIVESTATUS_CLASS_TRACE'} = 999 if $ENV{'THRUK_VERBOSE'} >= 4;

# no need to load extra modules for bash completion
my $action = $options->{'action'} || $options->{'commandoptions'}->[0] || '';
if($action eq 'bash_complete') {
    require Thruk::Utils::Bash;
    exit(Thruk::Utils::Bash::complete());
}

require Thruk::Utils::CLI;
&timing_breakpoint('modules loaded');
my $cli = Thruk::Utils::CLI->new($options);
exit $cli->_run();

##############################################
sub _print_modules {
    require Thruk::Config;
    require Thruk::Utils;
    # read the config which puts our loaded addons into @INC and those cli modules will be found as well
    Thruk::Config::set_config_env();
    print "Enabled cli plugins: ".join(", ", @{Thruk::Utils::get_cli_modules()})."\n";
    print "get help for a specific plugin with: $0 <plugin> help\n";
    return;
}

##############################################

1;
__END__

=head1 NAME

thruk - Command Line Utility for Thruk Monitoring Gui

=head1 SYNOPSIS

  Usage: thruk [globaloptions] <command> [commandoptions]

  Globaloptions:
    -h, --help                    Show this help message and exit
    -v, --verbose                 Print verbose output
    -q, --quiet                   Print less output
    -V, --version                 Print version

    -b, --backend=<backend>       Comma seperated list of backends/sites
                                  which should be used for querys.
    -A, --auth=<auth>             Set username for querys

    -c, --credential=<pw>         Credential when connecting to remote
                                  Thruk installations specified by the
                                  remote-url.
        --remote-url=<url>        URL to remote installation.
    -k, --insecure                skip ssl certificate verification.

    -y, --yes                     answer yes to all given questions.
    -f, --force                   some actions need to be forced

  Compatibility options:
        --list-commands           List available commands.
    -l, --list-backends           List available backends/sites. Alias for 'backend list'.
    -a, --action=<command>        Perform given action. see below for a list.


=head1 DESCRIPTION

This script gives access to various parts of the Thruk gui and allows to generate
excel reports, csv exports or any other url by using command line and bypassing the
webserver.

=head1 COMMANDS

Available commands will be listed when running thruk without any argument or by

  %> thruk --list-commands

=head1 GLOBALOPTIONS

script has the following arguments

=over 4

=item B<-h> , B<--help>

    print help and exit

=item B<-v> , B<--verbose>

    print verbose output too

=item B<-V> , B<--version>

    print version and exit

=item B<-b> I<backend>, B<--backend>=I<backend>

    specify backend(s), otherwise the default backends will be
    used. Specify the key of the backend. Use <-l> to get a list
    of backends.

    All default backends (backends without the 'hidden' flag) will be used unless
    backend(s) are specified with this option.

    Use 'ALL' to use all backends, regardless of the hidden flag.

=item B<-l> , B<--list-backends>

    get list of available backends

=item B<--list-commands>

    get list of available commands.

=item B<-a> I<action>, B<--action>=I<action>

    This is deprecated, use the new form 'thruk <cmd> ...' instead.

    perform selected action:

    Scheduling Commands
      - fix_scheduling(=filter)     balance scheduling or all hosts and services
                                    or just a group by adding a filter like
                                    fix_scheduling=hg:<hostgroup>
                                    fix_scheduling=sg:<servicegroup>

    Internal Commands
      - compile                     compile templates for faster access
      - clean_dashboards            remove empty dashboards which are older than 1 day
      - stop/restart                stop thruk process (restart assumes they will be restarted automatically from apache)



=item B<-A> I<authname>, B<--auth>=I<authname>

    use this username for authentication

=item B<-k>, B<--insecure>

    Skip ssl certificate verification when accessing remote url.

=item B<-y> , B<--yes>

    answer yes to a given questions during commands.

=back

=head1 RETURN VALUE

thruk returns 0 on success and >= 1 otherwise

=head1 EXAMPLES

List available backends:

  %> thruk -l

List available commands:

  %> thruk

=head1 AUTHOR

Sven Nierlein, 2009-present, <sven@nierlein.org>

=cut
