#!/usr/bin/env perl

use strict;
use warnings;
use Getopt::Long qw//;

eval "use inc::Module::Install";
if($@ && !-e 'Makefile') {
    print STDERR "Module::Install is required to build Thruk from source.\n\n";
    print STDERR $@;
    exit 1;
}

alarm(180);

my $options = {
  'prefix'          => '/usr/local',
  'htmlurl'         => '/thruk',
  'unsafeallow3f'   => '',
  'nounsafeallow3f' => '',
  'thruk-user'      => `id -un`,
  'thruk-group'     => `id -gn`,
  'httpd-conf'      => '',
  'logrotatedir'    => '',
  'bashcompldir'    => '',
  'quiet'           => 0,
};
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 { $options->{'verbose'}++ },
   "prefix=s"               => \$options->{'prefix'},
   "exec-prefix=s"          => \$options->{'eprefix'},
   "bindir=s"               => \$options->{'bindir'},
   "libdir=s"               => \$options->{'libdir'},
   "sysconfdir=s"           => \$options->{'sysconfdir'},
   "localstatedir=s"        => \$options->{'localstatedir'},
   "datadir=s"              => \$options->{'datadir'},
   "mandir=s"               => \$options->{'mandir'},
   "with-tempdir=s"         => \$options->{'tmpdir'},
   "with-initdir=s"         => \$options->{'initdir'},
   "with-logrotatedir=s"    => \$options->{'logrotatedir'},
   "with-logdir=s"          => \$options->{'logdir'},
   "with-htmlurl=s"         => \$options->{'htmlurl'},
   "with-httpd-conf=s"      => \$options->{'httpd-conf'},
   "with-unsafeallow3f"     => \$options->{'unsafeallow3f'},
   "without-unsafeallow3f"  => \$options->{'nounsafeallow3f'},
   "with-checkresultdir=s"  => \$options->{'checkresultdir'},
   "with-bashcompletedir=s" => \$options->{'bashcompldir'},
   "with-thruk-user=s"      => \$options->{'thruk-user'},
   "with-thruk-group=s"     => \$options->{'thruk-group'},
   "with-thruk-libs=s"      => \$options->{'thruk-libs'},
   "with-thruk-tempdir=s"   => \$options->{'thruk-tempdir'},
   "with-thruk-vardir=s"    => \$options->{'thruk-vardir'},
   "with-thruk-logdir=s"    => \$options->{'thruk-logdir'},
   "without-compress"       => \$options->{'nocompress'},
   "without-thruk-libs"     => \$options->{'nolibs'},
   "quiet|q"                => \$options->{'quiet'},
) or warn "error in options";

if($options->{'help'}) {
    require Pod::Usage;
    Pod::Usage::pod2usage( { -verbose => 2, -exit => 3 } );
}

if($options->{'nocompress'}) {
    warn("*** deprecated: --without-compress is deprecated and no longer required.");
}

$options->{'initdir'}         = $options->{'initdir'} || $options->{'prefix'}.'/etc/init.d';
$options->{'logdir'}          = $options->{'logdir'} || $options->{'prefix'}.'/var/log/thruk';
$options->{'thruk-libs'}      = $options->{'thruk-libs'} || $options->{'prefix'}.'/lib/thruk/perl5';
$options->{'checkresultdir'}  = $options->{'checkresultdir'} || $options->{'prefix'}.'/var/cache/naemon/checkresults';

$options->{'eprefix'}        = $options->{'prefix'}          unless $options->{'eprefix'};
$options->{'bindir'}         = $options->{'prefix'}.'/bin'   unless $options->{'bindir'};
$options->{'sysconfdir'}     = $options->{'prefix'}.'/etc'   unless $options->{'sysconfdir'};
$options->{'tmpdir'}         = $options->{'prefix'}.'/tmp'   unless $options->{'tmpdir'};
$options->{'localstatedir'}  = $options->{'prefix'}.'/var'   unless $options->{'localstatedir'};
$options->{'libdir'}         = $options->{'prefix'}.'/lib'   unless $options->{'libdir'};
$options->{'datadir'}        = $options->{'prefix'}.'/share' unless $options->{'datadir'};
$options->{'mandir'}         = $options->{'prefix'}.'/man'   unless $options->{'mandir'};

$options->{'tmpdir'}         = $options->{'thruk-tempdir'} if $options->{'thruk-tempdir'};
$options->{'localstatedir'}  = $options->{'thruk-vardir'}  if $options->{'thruk-vardir'};
$options->{'logdir'}         = $options->{'thruk-logdir'}  if $options->{'thruk-logdir'};

chomp($options->{'thruk-user'});
chomp($options->{'thruk-group'});

$options->{'htmlurl'}    =~ s|/+$||mx;
$options->{'htmlurl'}    =~ s|^/+||mx;
$options->{'htmlurl'}    = '/'.$options->{'htmlurl'};
$options->{'compress'}   = $options->{'nocompress'} ? 'disabled' : 'enabled';
$options->{'thruk-libs'} = '' if $options->{'nolibs'};

# recent apaches might require the UnsafeAllow3F flag
if(!$options->{'nounsafeallow3f'} && !$options->{'unsafeallow3f'}) {
    my($apache_bin, $module_dir) = _get_apache();
    if($apache_bin && $module_dir) {
        my $src = _read('./support/apache-test-unsafeallow.conf');
        require File::Temp;
        my($fh, $tmpfile) = File::Temp::tempfile();
        $src =~ s%###APACHE_MODULE_DIR###%$module_dir%g;
        print $fh $src;
        close($fh);
        my $cmd = "$apache_bin -t -f $tmpfile  2>&1";
        `$cmd 2>&1`;
        if($? == 0) {
            $options->{'unsafeallow3f'} = 1;
        }
        unlink($tmpfile);
    }
}
if($options->{'nounsafeallow3f'}) {
    $options->{'unsafeallow3f'} = '';
}
if($options->{'unsafeallow3f'}) {
    $options->{'unsafeallow3f'} = ',UnsafeAllow3F';
}

open(my $fh, '>', 'script/Makefile.options') or die("cannot write to: script/Makefile.options:".$!);
print $fh <<EOT;
### THRUK
PREFIX           = $options->{'prefix'}
EPREFIX          = $options->{'eprefix'}
BINDIR           = $options->{'bindir'}
SYSCONFDIR       = $options->{'sysconfdir'}
LIBDIR           = $options->{'libdir'}
TMPDIR           = $options->{'tmpdir'}
LOCALSTATEDIR    = $options->{'localstatedir'}
DATADIR          = $options->{'datadir'}
MANDIR           = $options->{'mandir'}
INITDIR          = $options->{'initdir'}
LOGROTATEDIR     = $options->{'logrotatedir'}
LOGDIR           = $options->{'logdir'}
HTMLURL          = $options->{'htmlurl'}
HTTPDCONF        = $options->{'httpd-conf'}
BASHCOMPLDIR     = $options->{'bashcompldir'}
THRUKUSER        = $options->{'thruk-user'}
THRUKGROUP       = $options->{'thruk-group'}
THRUKLIBS        = $options->{'thruk-libs'}
CHECKRESULTDIR   = $options->{'checkresultdir'}
THRUKCOMPRESS    = $options->{'compress'}
UNSAFEALLOW3F    = $options->{'unsafeallow3f'}

EOT

close($fh);
unlink("Makefile");
my $out = `yes n | $^X Makefile.PL 2>&1`;
if(!-e "Makefile") {
    print "configure failed:\n\n";
    print $out;
    exit 1;
}

# check our modules if not modules are build
if($options->{'nolibs'}) {
    $out = `make checkdeps 2>&1`;
    if($out =~ m/Warning:\sprerequisite/mx) {
        print $out;
        unlink("Makefile");
        print "ERROR: missing dependencies, see list above for details\n";
        exit 1;
    }
}

exit if $options->{'quiet'};

$options->{'httpd-conf'}    = '** not installed **' unless $options->{'httpd-conf'};
$options->{'logrotatedir'}  = '** not installed **' unless $options->{'logrotatedir'};
$options->{'bashcompldir'}  = '** not installed **' unless $options->{'bashcompldir'};
print <<EOT;

*************************************
* THRUK - configuration
*************************************

  eprefix            = $options->{'eprefix'}
  bindir             = $options->{'bindir'}
  sysconfdir         = $options->{'sysconfdir'}
  libdir             = $options->{'libdir'}
  tmpdir             = $options->{'tmpdir'}
  localstatedir      = $options->{'localstatedir'}
  datadir            = $options->{'datadir'}
  mandir             = $options->{'mandir'}

  initdir            = $options->{'initdir'}
  logrotatedir       = $options->{'logrotatedir'}
  logdir             = $options->{'logdir'}
  htmlurl            = $options->{'htmlurl'}
  httpd-conf         = $options->{'httpd-conf'}
  unsafeallow3f      = $options->{'unsafeallow3f'}
  thruk-user         = $options->{'thruk-user'}
  thruk-group        = $options->{'thruk-group'}
  thruk-libs         = $options->{'thruk-libs'}
  checkresultdir     = $options->{'checkresultdir'}

now run
  make
  make install
to install thruk with these settings.

EOT

exit;

# try to detect apache
sub _get_apache {
    my($apache_bin, $module_dir);

    for my $bin (qw(/sbin/apache2 /usr/sbin/apache2 /usr/sbin/httpd usr/sbin/httpd2-prefork)) {
        if(-x $bin) {
            $apache_bin = $bin;
            last;
        }
    }

    for my $dir (qw(/usr/lib64/httpd/modules /usr/lib/apache2/modules /usr/lib64/apache2-prefork /usr/lib64/httpd/modules)) {
        if(-x $dir) {
            $module_dir = $dir;
            last;
        }
    }

    return($apache_bin, $module_dir);
}

sub _read {
    my($file) = @_;
    local $/ = undef;
    open(my $fh, '<', $file) or die("cannot read file: $file: $!");
    my $data = <$fh>;
    close($fh);
    return $data;
}

1;
__END__
##############################################

=head1 SYNOPSIS

  Usage: configure [options]

  Options:

    -h, --help                    Show this help message and exit
    -v, --verbose                 Print verbose output

  Installation directories:

    --prefix=PREFIX               install architecture-independent files in PREFIX
                                  [/usr/local]

    --exec-prefix=EPREFIX         install architecture-dependent files in EPREFIX
                                  [PREFIX]

  By default, `make install' will install all the files in
  `/usr/local/bin', `/usr/local/lib' etc.  You can specify
  an installation prefix other than `/usr/local/' using `--prefix',
  for instance `--prefix=$HOME'.

  For better control, use the options below.

  Fine tuning of the installation directories:
    --bindir=DIR                 user executables [EPREFIX/bin]
    --sysconfdir=DIR             read-only single-machine data [PREFIX/etc]
    --localstatedir=DIR          modifiable single-machine data [PREFIX/var]
    --libdir=DIR                 object code libraries [EPREFIX/lib]
    --datadir=DIR                read-only architecture-independent data [PREFIX/share]
    --mandir=DIR                 man documentation [DATADIR/man]

  Optional Settings:

    --with-htmlurl=<local-url>   sets URL for public html [/thruk]

    --with-tempdir               sets the temp folder [PREFIX/tmp]
    --with-initdir               sets the folder for rc scripts
    --with-httpd-conf            sets path to Apache conf.d directory
    --with-logrotatedir          sets path to logrotates.d directory
    --with-logdir                sets path to log files [PREFIX/var/log/thruk]
    --with-thruk-libs            sets path to thruk libs directory [PREFIX/lib/thruk/perl5]
    --with-thruk-user            sets user name to run thruk [thruk]
    --with-thruk-group           sets group name to run thruk [thruk]
    --with-checkresultdir        sets path to Naemon/Nagios/Icinga/Shinken checkresult directory [PREFIX/var/cache/naemon/checkresults]
    --without-thruk-libs         skip building the required perl modules. Make sure you add dependencies accordingly

    --with(out)-unsafeallow3f    enable/disable apache mod_rewrite flag UnsafeAllow3F

=cut
