#!/usr/bin/env perl

#
# InspIRCd -- Internet Relay Chat Daemon
#
#   Copyright (C) 2012-2017 Peter Powell <petpow@saberuk.com>
#   Copyright (C) 2009-2010 Daniel De Graaf <danieldg@inspircd.org>
#   Copyright (C) 2007, 2009 Dennis Friis <peavey@inspircd.org>
#   Copyright (C) 2003, 2006-2008 Craig Edwards <craigedwards@brainbox.cc>
#   Copyright (C) 2006-2008 Robin Burchell <robin+git@viroteck.net>
#   Copyright (C) 2008 Thomas Stagner <aquanight@inspircd.org>
#   Copyright (C) 2007 John Brooks <john.brooks@dereferenced.net>
#   Copyright (C) 2006 Oliver Lupton <oliverlupton@gmail.com>
#   Copyright (C) 2003-2006 Craig McLure <craig@chatspike.net>
#
# This file is part of InspIRCd.  InspIRCd is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#


BEGIN {
	require 5.10.0;
}

use feature ':5.10';
use strict;
use warnings FATAL => qw(all);

use File::Basename        qw(basename);
use File::Copy            ();
use File::Spec::Functions qw(rel2abs);
use FindBin               qw($RealDir);
use Getopt::Long          qw(GetOptions);
use POSIX                 qw(getgid getuid);

use lib $RealDir;
use make::common;
use make::configure;
use make::console;
use make::directive;

my ($opt_binary_dir,
    $opt_config_dir,
    $opt_data_dir,
    $opt_development,
    $opt_disable_interactive,
    $opt_distribution_label,
    $opt_gid,
    $opt_log_dir,
    $opt_manual_dir,
    $opt_module_dir,
    $opt_prefix,
    $opt_script_dir,
    $opt_socketengine,
    $opt_system,
    $opt_uid);

sub list_extras ();

sub enable_extras (@);

sub disable_extras (@);

my @opt_enableextras;
my @opt_disableextras;

GetOptions(
	'clean'  => \&cmd_clean,
	'help'	 => \&cmd_help,
	'update' => \&cmd_update,

	'development'          => \$opt_development,
	'disable-interactive'  => \$opt_disable_interactive,
	'distribution-label=s' => \$opt_distribution_label,
	'binary-dir=s'         => \$opt_binary_dir,
	'config-dir=s'         => \$opt_config_dir,
	'data-dir=s'           => \$opt_data_dir,
	'gid=s'                => \$opt_gid,
	'log-dir=s'            => \$opt_log_dir,
	'manual-dir=s'         => \$opt_manual_dir,
	'module-dir=s'         => \$opt_module_dir,
	'prefix=s'             => \$opt_prefix,
	'script-dir=s'         => \$opt_script_dir,
	'socketengine=s'       => \$opt_socketengine,
	'system'               => \$opt_system,
	'uid=s'                => \$opt_uid,

	# TODO: when the modulemanager rewrite is done these should be removed.
	'disable-extras=s@' => \@opt_disableextras,
	'enable-extras=s@'  => \@opt_enableextras,
	'list-extras'       => sub { list_extras; exit 0; },
);

if (scalar(@opt_enableextras) + scalar(@opt_disableextras) > 0) {
	@opt_enableextras = split /,/, join(',', @opt_enableextras);
	@opt_disableextras = split /,/, join(',', @opt_disableextras);
	enable_extras(@opt_enableextras);
	disable_extras(@opt_disableextras);
	list_extras;
	print "Remember: YOU are responsible for making sure any libraries needed have been installed!\n";
	exit 0;
}

our $interactive = !(
	!-t STDIN ||
	!-t STDOUT ||
	defined $opt_binary_dir ||
	defined $opt_config_dir ||
	defined $opt_data_dir ||
	defined $opt_development ||
	defined $opt_disable_interactive ||
	defined $opt_distribution_label ||
	defined $opt_gid ||
	defined $opt_log_dir ||
	defined $opt_manual_dir ||
	defined $opt_module_dir ||
	defined $opt_prefix ||
	defined $opt_script_dir ||
	defined $opt_socketengine ||
	defined $opt_system ||
	defined $opt_uid
);

my %version = get_version $opt_distribution_label;
print_format "<|BOLD Configuring InspIRCd $version{FULL} on $^O.|>\n";

my %config;
if ($interactive) {
	%config = read_config_file(CONFIGURE_CACHE_FILE);
	run_test CONFIGURE_CACHE_FILE, %config;
	if (!defined $config{VERSION}) {
		$config{VERSION} = CONFIGURE_CACHE_VERSION;
	} elsif ($config{VERSION} != CONFIGURE_CACHE_VERSION) {
		print_warning "ignoring contents of ${\CONFIGURE_CACHE_FILE} as it was generated by an incompatible version of $0!";
		%config = ('VERSION', CONFIGURE_CACHE_VERSION);
	}
}

$config{CXX} = find_compiler($config{CXX} // $ENV{CXX});
unless ($config{CXX}) {
	say 'A suitable C++ compiler could not be detected on your system!';
	unless ($interactive) {
		say 'Set the CXX environment variable to the path to a C++ compiler binary if this is incorrect.';
		exit 1;
	}
	until ($config{CXX}) {
		my $compiler_path = prompt_string 1, 'Please enter the path to a C++ compiler binary:', 'c++';
		$config{CXX} = find_compiler $compiler_path;
	}
}
my %compiler = get_compiler_info($config{CXX});

$config{HAS_CLOCK_GETTIME} = run_test 'clock_gettime()', test_file($config{CXX}, 'clock_gettime.cpp', $^O eq 'darwin' ? undef : '-lrt');
$config{HAS_EVENTFD} = run_test 'eventfd()', test_file($config{CXX}, 'eventfd.cpp');

my @socketengines;
push @socketengines, 'epoll'  if run_test 'epoll', test_header $config{CXX}, 'sys/epoll.h';
push @socketengines, 'kqueue' if run_test 'kqueue', test_file $config{CXX}, 'kqueue.cpp';
push @socketengines, 'poll'   if run_test 'poll', test_header $config{CXX}, 'poll.h';
push @socketengines, 'select';

if (defined $opt_socketengine) {
	unless (grep { $_ eq $opt_socketengine } @socketengines) {
		my $reason = -f "src/socketengines/socketengine_$opt_socketengine.cpp" ? 'is not available on this platform' : 'does not exist';
		print_error "The socket engine you requested ($opt_socketengine) $reason!",
			'Available socket engines are:',
			map { "  * $_" } @socketengines;
	}
}
$config{SOCKETENGINE} = $opt_socketengine // $socketengines[0];

if (defined $opt_system) {
	$config{BASE_DIR}   = $opt_prefix     // '/var/lib/inspircd';
	$config{BINARY_DIR} = $opt_binary_dir // '/usr/sbin';
	$config{CONFIG_DIR} = $opt_config_dir // '/etc/inspircd';
	$config{DATA_DIR}   = $opt_data_dir   // '/var/inspircd';
	$config{LOG_DIR}    = $opt_module_dir // '/var/log/inspircd';
	$config{MANUAL_DIR} = $opt_manual_dir // '/usr/share/man/man1';
	$config{MODULE_DIR} = $opt_module_dir // '/usr/lib/inspircd';
	$config{SCRIPT_DIR} = $opt_script_dir // '/usr/share/inspircd'
} else {
	$config{BASE_DIR}   = $opt_prefix     // $config{BASE_DIR}   // rel2abs 'run';
	$config{BINARY_DIR} = $opt_binary_dir // $config{BINARY_DIR} // rel2abs $config{BASE_DIR} . '/bin';
	$config{CONFIG_DIR} = $opt_config_dir // $config{CONFIG_DIR} // rel2abs $config{BASE_DIR} . '/conf';
	$config{DATA_DIR}   = $opt_data_dir   // $config{DATA_DIR}   // rel2abs $config{BASE_DIR} . '/data';
	$config{LOG_DIR}    = $opt_log_dir    // $config{LOG_DIR}    // rel2abs $config{BASE_DIR} . '/logs';
	$config{MANUAL_DIR} = $opt_manual_dir // $config{MANUAL_DIR} // rel2abs $config{BASE_DIR} . '/manuals';
	$config{MODULE_DIR} = $opt_module_dir // $config{MODULE_DIR} // rel2abs $config{BASE_DIR} . '/modules';
	$config{SCRIPT_DIR} = $opt_script_dir // $config{SCRIPT_DIR} // $config{BASE_DIR};
}

# Parse --gid=123 or --gid=foo and extract the group id.
my @group;
if (defined $opt_gid) {
	@group = $opt_gid =~ /^\d+$/ ? getgrgid($opt_gid) : getgrnam($opt_gid);
	print_error "there is no '$opt_gid' group on this system!" unless @group;
} else {
	@group = $opt_system ? getgrnam('irc') : getgrgid($config{GID} // getgid());
	print_error "you need to specify a group to run as using '--gid [id|name]'!" unless @group;
}
$config{GROUP} = $group[0];
$config{GID}   = $group[2];

# Parse --uid=123 or --uid=foo and extract the user id.
my @user;
if (defined $opt_uid) {
	@user = $opt_uid =~ /^\d+$/ ? getpwuid($opt_uid) : getpwnam($opt_uid);
	print_error "there is no '$opt_uid' user on this system!" unless @user;
} else {
	@user = $opt_system ? getpwnam('irc') : getpwuid($config{UID} // getuid());
	print_error "you need to specify a user to run as using '--uid [id|name]'!" unless @user;
}
$config{USER} = $user[0];
$config{UID}  = $user[2];

# Clear the screen.
system 'tput', 'clear' if $interactive;

# Warn the user about clock drifting when running on OpenVZ.
if (-e '/proc/user_beancounters' || -e '/proc/vz/vzaquota') {
	print_warning <<'EOW';
You are building InspIRCd inside of an an OpenVZ container. If you
plan to use InspIRCd in this container then you should make sure that NTP is
configured on the Hardware Node. Failure to do so may result in clock drifting!
EOW
}

# Check that the user actually wants this version.
if ($version{LABEL} ne 'release') {
	print_warning <<'EOW';
You are building a development version. This contains code which has
not been tested as heavily and may contain various faults which could seriously
affect the running of your server. It is recommended that you use a stable
version instead.

You can obtain the latest stable version from http://www.inspircd.org/ or by
running `git checkout insp20` if you are installing from Git.
EOW
	if (!prompt_bool $interactive, 'I understand this warning and want to continue anyway.', $opt_development // 0) {
		say STDERR 'If you understand this warning and still want to continue pass the --development flag.' unless $interactive;
		exit 1;
	}
}

# Configure directory settings.
my $question = <<"EOQ";
Currently, InspIRCd is configured with the following paths:

<|BOLD Base:|>   $config{BASE_DIR}
<|BOLD Binary:|> $config{BINARY_DIR}
<|BOLD Config:|> $config{CONFIG_DIR}
<|BOLD Data:|>   $config{DATA_DIR}
<|BOLD Log:|>    $config{LOG_DIR}
<|BOLD Manual:|> $config{MANUAL_DIR}
<|BOLD Module:|> $config{MODULE_DIR}
<|BOLD Script:|> $config{SCRIPT_DIR}

Do you want to change these settings?
EOQ
if (prompt_bool $interactive, $question, 0) {
	my $original_base_dir = $config{BASE_DIR};
	$config{BASE_DIR} = prompt_dir $interactive, 'In what directory do you wish to install the InspIRCd base?', $config{BASE_DIR};
	foreach my $key (qw(BINARY_DIR CONFIG_DIR DATA_DIR LOG_DIR MANUAL_DIR MODULE_DIR SCRIPT_DIR)) {
		$config{$key} =~ s/^\Q$original_base_dir\E/$config{BASE_DIR}/;
	}
	$config{BINARY_DIR} = prompt_dir $interactive, 'In what directory should the InspIRCd binary be placed?', $config{BINARY_DIR};
	$config{CONFIG_DIR} = prompt_dir $interactive, 'In what directory are configuration files to be stored?', $config{CONFIG_DIR};
	$config{DATA_DIR}   = prompt_dir $interactive, 'In what directory are variable data files to be stored?', $config{DATA_DIR};
	$config{LOG_DIR}    = prompt_dir $interactive, 'In what directory are log files to be stored?',           $config{LOG_DIR};
	$config{MANUAL_DIR} = prompt_dir $interactive, 'In what directory are manual pages to be placed?',        $config{MANUAL_DIR};
	$config{MODULE_DIR} = prompt_dir $interactive, 'In what directory are modules to be placed?',             $config{MODULE_DIR};
	$config{SCRIPT_DIR} = prompt_dir $interactive, 'In what directory are scripts to be placed?',             $config{SCRIPT_DIR};
}

# Configure module settings.
$question = <<'EOQ';
Currently, InspIRCd is configured to automatically enable all available extra modules.

Would you like to enable extra modules manually?
EOQ
if (prompt_bool $interactive, $question, 0) {
	foreach my $extra (<src/modules/extra/m_*.cpp>) {
		my $module_name = basename $extra, '.cpp';
		if (prompt_bool $interactive, "Would you like to enable $module_name?", 0) {
			enable_extras "$module_name.cpp";
		}
	}
} else {
	# TODO: finish modulemanager rewrite and replace this code with:
	# system './modulemanager', 'enable', '--auto';
	enable_extras 'm_ssl_gnutls.cpp' unless system 'pkg-config --exists gnutls >/dev/null 2>&1';
	enable_extras 'm_ssl_mbedtls.cpp' if -e '/usr/include/mbedtls/ssl.h';
	enable_extras 'm_ssl_openssl.cpp' unless system 'pkg-config --exists openssl >/dev/null 2>&1';
}

# Generate SSL certificates.
if (<src/modules/m_ssl_*.cpp> && prompt_bool $interactive, 'Would you like to generate SSL certificates now?', $interactive) {
	system './tools/genssl', 'auto';
}

# Cache the distribution label so that its not lost when --update is run.
$config{DISTRIBUTION} = $opt_distribution_label if $opt_distribution_label;

write_configure_cache %config;
parse_templates \%config, \%compiler, \%version;

print_format <<"EOM";

Configuration is complete! You have chosen to build with the following settings:

<|GREEN Compiler:|>
  <|GREEN Binary:|>  $config{CXX}
  <|GREEN Name:|>    $compiler{NAME}
  <|GREEN Version:|> $compiler{VERSION}

<|GREEN Extra Modules:|>
EOM

for my $file (<src/modules/m_*>) {
	my $module = basename $file, '.cpp';
	say "  * $module" if -l $file;
}

print_format <<"EOM";

<|GREEN Paths:|>
  <|GREEN Base:|>   $config{BASE_DIR}
  <|GREEN Binary:|> $config{BINARY_DIR}
  <|GREEN Config:|> $config{CONFIG_DIR}
  <|GREEN Data:|>   $config{DATA_DIR}
  <|GREEN Log:|>    $config{LOG_DIR}
  <|GREEN Manual:|> $config{MANUAL_DIR}
  <|GREEN Module:|> $config{MODULE_DIR}
  <|GREEN Script:|> $config{SCRIPT_DIR}

<|GREEN Execution Group:|> $config{GROUP} ($config{GID})
<|GREEN Execution User:|>  $config{USER} ($config{UID})
<|GREEN Socket Engine:|>   $config{SOCKETENGINE}

To build with these settings run '<|GREEN make -j${\get_cpu_count}|>' now.

EOM

# Routine to list out the extra/ modules that have been enabled.
# Note: when getting any filenames out and comparing, it's important to lc it if the
# file system is not case-sensitive (== Epoc, MacOS, OS/2 (incl DOS/DJGPP), VMS, Win32
# (incl NetWare, Symbian)). Cygwin may or may not be case-sensitive, depending on
# configuration, however, File::Spec does not currently tell us (it assumes Unix behavior).
sub list_extras () {
	use File::Spec;
	# @_ not used
	my $srcdir = File::Spec->catdir("src", "modules");
	my $abs_srcdir = File::Spec->rel2abs($srcdir);
	local $_;
	my $dd;
	opendir $dd, File::Spec->catdir($abs_srcdir, "extra") or die (File::Spec->catdir($abs_srcdir, "extra") . ": $!\n");
	my @extras = map { File::Spec->case_tolerant() ? lc($_) : $_ } (readdir($dd));
	closedir $dd;
	undef $dd;
	opendir $dd, $abs_srcdir or die "$abs_srcdir: $!\n";
	my @sources = map { File::Spec->case_tolerant() ? lc($_) : $_ } (readdir($dd));
	closedir $dd;
	undef $dd;
	my $maxlen = (sort { $b <=> $a } (map {length($_)} (@extras)))[0];
	my %extras = ();
EXTRA:	for my $extra (@extras) {
		next if (File::Spec->curdir() eq $extra || File::Spec->updir() eq $extra);
		my $abs_extra = File::Spec->catfile($abs_srcdir, "extra", $extra);
		my $abs_source = File::Spec->catfile($abs_srcdir, $extra);
		next unless ($extra =~ m/\.(cpp|h)$/ || (-d $abs_extra)); # C++ Source/Header, or directory
		if (-l $abs_source) {
			# Symlink, is it in the right place?
			my $targ = readlink($abs_source);
			my $abs_targ = File::Spec->rel2abs($targ, $abs_srcdir);
			if ($abs_targ eq $abs_extra) {
				$extras{$extra} = "\e[32;1menabled\e[0m";
			} else {
				$extras{$extra} = sprintf("\e[31;1mwrong symlink target (%s)\e[0m", $abs_targ);
			}
		} elsif (-e $abs_source) {
			my ($devext, $inoext) = stat($abs_extra);
			my ($devsrc, $inosrc, undef, $lnksrc) = stat($abs_source);
			if ($lnksrc > 1) {
				if ($devsrc == $devext && $inosrc == $inoext) {
					$extras{$extra} = "\e[32;1menabled\e[0m";
				} else {
					$extras{$extra} = sprintf("\e[31;1mwrong hardlink target (%d:%d)\e[0m", $devsrc, $inosrc);
				}
			} else {
				open my $extfd, "<", $abs_extra;
				open my $srcfd, "<", $abs_source;
				local $/ = undef;
				if (scalar(<$extfd>) eq scalar(<$srcfd>)) {
					$extras{$extra} = "\e[32;1menabled\e[0m";
				} else {
					$extras{$extra} = sprintf("\e[31;1mout of synch (re-copy)\e[0m");
				}
			}
		} else {
			$extras{$extra} = "\e[33;1mdisabled\e[0m";
		}
	}
	# Now let's add dependency info
	for my $extra (keys(%extras)) {
		next unless $extras{$extra} =~ m/enabled/; # only process enabled extras.
		my $abs_extra = File::Spec->catfile($abs_srcdir, "extra", $extra);
		my @deps = split /\s+/, get_directive($abs_extra, 'ModDep', '');
		for my $dep (@deps) {
			if (exists($extras{$dep})) {
				my $ref = \$extras{$dep}; # Take reference.
				if ($$ref !~ m/needed by/) {
					# First dependency found.
					if ($$ref =~ m/enabled/) {
						$$ref .= " (needed by \e[32;1m$extra\e[0m";
					} else {
						$$ref =~ s/\e\[.*?m//g; # Strip out previous coloring. Will be set in bold+red+blink later.
						$$ref .= " (needed by \e[0;32;1;5m$extra\e[0;31;1;5m";
					}
				} else {
					if ($$ref =~ m/enabled/) {
						$$ref .= ", \e[32;1m$extra\e[0m";
					} else {
						$$ref .= ", \e[0;32;1;5m$extra\e[0;31;1;5m";
					}
				}
			}
		}
	}
	for my $extra (sort {$a cmp $b} keys(%extras)) {
		my $text = $extras{$extra};
		if ($text =~ m/needed by/ && $text !~ m/enabled/) {
			printf "\e[31;1;5m%-*s = %s%s\e[0m\n", $maxlen, $extra, $text, ($text =~ m/needed by/ ? ")" : "");
		} else {
			printf "%-*s = %s%s\n", $maxlen, $extra, $text, ($text =~ m/needed by/ ? "\e[0m)" : "");
		}
	}
	return keys(%extras) if wantarray; # Can be used by manage_extras.
}

sub enable_extras (@) {
	my (@extras) = @_;
	for my $extra (@extras) {
		my $extrapath = "src/modules/extra/$extra";
		if (!-e $extrapath) {
			print STDERR "Cannot enable \e[32;1m$extra\e[0m : No such file or directory in src/modules/extra\n";
			next;
		}
		my $source = "src/modules/$extra";
		if (-e $source) {
			print STDERR "Cannot enable \e[32;1m$extra\e[0m : destination in src/modules exists (might already be enabled?)\n";
			next;
		}
		# Get dependencies, and add them to be processed.
		my @deps = split /\s+/, get_directive($extrapath, 'ModDep', '');
		for my $dep (@deps) {
			next if scalar(grep { $_ eq $dep } (@extras)) > 0; # Skip if we're going to be enabling it anyway.
			if (!-e "src/modules/$dep" && !-e "include/$dep") {
				if (-e "src/modules/extra/$dep") {
					print STDERR "Will also enable extra \e[32;1m$dep\e[0m (needed by \e[32;1m$extra\e[0m)\n";
					push @extras, $dep;
				} else {
					print STDERR "\e[33;1mWARNING:\e[0m module \e[32;1m$extra\e[0m might be missing dependency \e[32;1m$dep\e[0m - YOU are responsible for satisfying it!\n";
				}
			}
		}
		print "Enabling $extra ... \n";
		symlink "extra/$extra", $source or print STDERR "$source: Cannot link to 'extra/$extra': $!\n";
	}
}

sub disable_extras (@)
{
	opendir my $dd, "src/modules/extra/";
	my @files = readdir($dd);
	closedir $dd;
	my (@extras) = @_;
EXTRA:	for my $extra (@extras) {
		my $extrapath = "src/modules/extra/$extra";
		my $source = "src/modules/$extra";
		if (!-e $extrapath) {
			print STDERR "Cannot disable \e[32;1m$extra\e[0m : Is not an extra\n";
			next;
		}
		if ((! -l $source) || readlink($source) ne "extra/$extra") {
			print STDERR "Cannot disable \e[32;1m$extra\e[0m : Source is not a link or doesn't refer to the right file. Remove manually if this is in error.\n";
			next;
		}
		# Check if anything needs this.
		for my $file (@files) {
			my @deps = split /\s+/, get_directive("src/modules/extra/$file", 'ModDep', '');
			# File depends on this extra...
			if (scalar(grep { $_ eq $extra } @deps) > 0) {
				# And is both enabled and not about to be disabled.
				if (-e "src/modules/$file" && scalar(grep { $_ eq $file } @extras) < 1) {
					print STDERR "Cannot disable \e[32;1m$extra\e[0m : is needed by \e[32;1m$file\e[0m\n";
					next EXTRA;
				}
			}
		}
		# Now remove.
		print "Disabling $extra ... \n";
		unlink "src/modules/$extra" or print STDERR "Cannot disable \e[32;1m$extra\e[0m : $!\n";
	}
}
