#!/usr/bin/env perl

#
# InspIRCd -- Internet Relay Chat Daemon
#
#   Copyright (C) 2009-2010 Daniel De Graaf <danieldg@inspircd.org>
#
# 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/>.
#


use strict;
use POSIX;
use Fcntl;

my $basepath	=	"@BASE_DIR@";
my $confpath	=	"@CONFIG_DIR@/";
my $binpath	=	"@BINARY_DIR@";
my $runpath	=	"@BASE_DIR@";
my $datadir	=       "@DATA_DIR@";
my $valgrindlogpath	=	"$basepath/valgrindlogs";
my $executable	=	"@EXECUTABLE@";
my $version	=	"@VERSION@";
my $uid = "@UID@";

if ($< == 0 || $> == 0) {
	if ($uid !~ /^\d+$/) {
		# Named UID, look it up
		$uid = getpwnam $uid;
	}
	if (!$uid) {
		die "Cannot find a valid UID to change to";
	}
	# drop root if we were configured with an ircd UID
	$< = $uid;
	$> = $uid;
	if ($< == 0 || $> == 0) {
		die "Could not drop root: $!";
	}
}

our($pid,$pidfile);
# Lets see what they want to do.. Set the variable (Cause i'm a lazy coder)
my $arg = shift(@ARGV);
my $conf;
for my $a (@ARGV)
{
	if ($a =~ m/^--config=(.*)$/)
	{
		$conf = $1;
		last;
	}
}
if (!defined $conf) {
	$conf = $confpath . "inspircd.conf";
	push @ARGV, '--config='.$conf;
}

getpidfile($conf);

# System for naming script command subs:
# cmd_<name> - Normal command for use by users.
# dev_<name> - Developer commands.
# hid_<name> - Hidden commands (ie Cheese-Sandwich)
# Ideally command subs shouldn't return.

my $subname = $arg;
$subname =~ s/-/_/g;
my $sub = main->can("cmd_$subname") || main->can("dev_$subname") || main->can("hid_$subname");
if (!defined($sub))
{
	print STDERR "Invalid command or none given.\n";
	cmd_help();
	exit 1;
}
else
{
	$sub->(@ARGV);
	exit 0;
}

sub cmd_help()
{
	my @subs = grep { $_ =~ m/^(cmd|dev)_/ && defined(main->can($_)) } keys(%::);
	my @cmds = grep /^cmd_/, @subs;
	my @devs = grep /^dev_/, @subs;
	local $_;
	$_ =~ s/^(cmd|dev)_// foreach (@cmds, @devs);
	$_ =~ s/_/-/g foreach (@cmds, @devs);
	print STDERR "Usage: ./inspircd (" . join("|", @cmds) . ")\n";
	print STDERR "Developer arguments: (" . join("|", @devs) . ")\n";
	exit 0;
}

sub cmd_status()
{
	if (getstatus() == 1) {
		my $pid = getprocessid();
		print "InspIRCd is running (PID: $pid)\n";
		exit();
	} else {
		print "InspIRCd is not running. (Or PID File not found)\n";
		exit();
	}
}

sub cmd_rehash()
{
	if (getstatus() == 1) {
		my $pid = getprocessid();
		system("kill -HUP $pid >/dev/null 2>&1");
		print "InspIRCd rehashed (pid: $pid).\n";
		exit();
	} else {
		print "InspIRCd is not running. (Or PID File not found)\n";
		exit();
	}
}

sub cmd_cron()
{
	if (getstatus() == 0) { goto &cmd_start(); }
	exit();
}

sub cmd_version()
{
	print "InspIRCd version: $version\n";
	exit();
}

sub cmd_restart(@)
{
	cmd_stop();
	unlink($pidfile) if (-e $pidfile);
	goto &cmd_start;
}

sub hid_cheese_sandwich()
{
	print "Creating Cheese Sandwich..\n";
	print "Done.\n";
	exit();
}

sub cmd_start(@)
{
	# Check to see its not 'running' already.
	if (getstatus() == 1) { print "InspIRCd is already running.\n"; return 0; }
	# If we are still alive here.. Try starting the IRCd..
	chdir $runpath;
	print "$binpath/$executable doesn't exist\n" and return 0 unless(-e "$binpath/$executable");
	print "$binpath/$executable is not executable\n" and return 0 unless(-f "$binpath/$executable" && -x "$binpath/$executable");

	exec "$binpath/$executable", @_;
	die "Failed to start IRCd: $!\n";
}

sub dev_debug(@)
{
	# Check to see its not 'running' already.
	if (getstatus() == 1) { print "InspIRCd is already running.\n"; return 0; }

	chdir $runpath;
	print "$binpath/$executable doesn't exist\n" and return 0 unless(-e "$binpath/$executable");
	print "$binpath/$executable is not executable\n" and return 0 unless(-f "$binpath/$executable" && -x "$binpath/$executable");

	# Check we have gdb
	checkgdb();

	# If we are still alive here.. Try starting the IRCd..
	exec 'gdb', "--command=$basepath/.gdbargs", '--args', "$binpath/$executable", qw(--nofork --debug), @_;
	die "Failed to start GDB: $!\n";
}

sub dev_screendebug(@)
{
	# Check to see its not 'running' already.
	if (getstatus() == 1) { print "InspIRCd is already running.\n"; return 0; }

	chdir $runpath;
	print "$binpath/$executable doesn't exist\n" and return 0 unless(-e "$binpath/$executable");

	#Check we have gdb
	checkgdb();
	checkscreen();

	# If we are still alive here.. Try starting the IRCd..
	print "Starting InspIRCd in `screen`, type `screen -r` when the ircd crashes to view the gdb output and get a backtrace.\n";
	print "Once you're inside the screen session press ^C + d to re-detach from the session\n";
	exec qw(screen -m -d gdb), "--command=$basepath/.gdbargs", '-args', "$binpath/$executable", qw(--nofork --debug --nolog), @_;
	die "Failed to start screen: $!\n";
}

sub dev_valdebug(@)
{
	# Check to see its not 'running' already.
	if (getstatus() == 1) { print "InspIRCd is already running.\n"; return 0; }

	chdir $runpath;
	print "$binpath/$executable doesn't exist\n" and return 0 unless(-e "$binpath/$executable");
	print "$binpath/$executable is not executable\n" and return 0 unless(-f "$binpath/$executable" && -x "$binpath/$executable");

	# Check we have valgrind and gdb
	checkvalgrind();
	checkgdb();

	# If we are still alive here.. Try starting the IRCd..
	# May want to do something with these args at some point: --suppressions=.inspircd.sup --gen-suppressions=yes
	# Could be useful when we want to stop it complaining about things we're sure aren't issues.
	exec qw(valgrind -v --tool=memcheck --leak-check=yes --db-attach=yes --num-callers=10), "$binpath/$executable", qw(--nofork --debug --nolog), @_;
	die "Failed to start valgrind: $!\n";
}

sub dev_valdebug_unattended(@)
{
	# NOTE: To make sure valgrind generates coredumps, set soft core limit in /etc/security/limits.conf to unlimited
	# Check to see its not 'running' already.
	if (getstatus() == 1) { print "InspIRCd is already running.\n"; return 0; }

	chdir $runpath;
	print "$binpath/$executable doesn't exist\n" and return 0 unless(-e "$binpath/$executable");
	print "$binpath/$executable is not executable\n" and return 0 unless(-f "$binpath/$executable" && -x "$binpath/$executable");

	# Check we have valgrind and gdb
	checkvalgrind();
	checkgdb();

	# If we are still alive here.. Try starting the IRCd..
	#
	# NOTE: Saving the debug log (redirected stdout), while useful, is a potential security risk AND one hell of a spacehog. DO NOT SAVE THIS WHERE EVERYONE HAS ACCESS!
	# Redirect stdout to /dev/null if you're worried about the security.
	#
	my $pid = fork;
	if ($pid == 0) {
		POSIX::setsid();
		-d $valgrindlogpath or mkdir $valgrindlogpath or die "Cannot create $valgrindlogpath: $!\n";
		-e "$binpath/valgrind.sup" or do { open my $f, '>', "$binpath/valgrind.sup"; };
		my $suffix = strftime("%Y%m%d-%H%M%S", localtime(time)) . ".$$";
		open STDIN, '<', '/dev/null' or die "Can't redirect STDIN to /dev/null: $!\n";
		sysopen STDOUT, "$valgrindlogpath/out.$suffix", O_WRONLY | O_CREAT | O_NOCTTY | O_APPEND, 0600 or die "Can't open $valgrindlogpath/out.$suffix: $!\n";
		sysopen STDERR, "$valgrindlogpath/valdebug.$suffix", O_WRONLY | O_CREAT | O_NOCTTY | O_APPEND, 0666 or die "Can't open $valgrindlogpath/valdebug.$suffix: $!\n";
	# May want to do something with these args at some point: --suppressions=.inspircd.sup --gen-suppressions=yes
	# Could be useful when we want to stop it complaining about things we're sure aren't issues.
		exec qw(valgrind -v --tool=memcheck --leak-check=full --show-reachable=yes --num-callers=15 --track-fds=yes),
			"--suppressions=$binpath/valgrind.sup", qw(--gen-suppressions=all),
			qw(--leak-resolution=med --time-stamp=yes --log-fd=2 --),
			"$binpath/$executable", qw(--nofork --debug --nolog), @_;
		die "Can't execute valgrind: $!\n";
	}
}

sub dev_screenvaldebug(@)
{
	# Check to see its not 'running' already.
	if (getstatus() == 1) { print "InspIRCd is already running.\n"; return 0; }

	chdir $runpath;
	print "$binpath/$executable doesn't exist\n" and return 0 unless(-e "$binpath/$executable");
	print "$binpath/$executable is not executable\n" and return 0 unless(-f "$binpath/$executable" && -x "$binpath/$executable");

	#Check we have gdb
	checkvalgrind();
	checkgdb();
	checkscreen();

	# If we are still alive here.. Try starting the IRCd..
	print "Starting InspIRCd in `screen`, type `screen -r` when the ircd crashes to view the valgrind and gdb output and get a backtrace.\n";
	print "Once you're inside the screen session press ^C + d to re-detach from the session\n";
	exec qw(screen -m -d valgrind -v --tool=memcheck --leak-check=yes --db-attach=yes --num-callers=10), "$binpath/$executable", qw(--nofork --debug --nolog), @_;
	die "Failed to start screen: $!\n";
}

sub cmd_stop()
{
	if (getstatus() == 0) { print "InspIRCd is not running. (Or PID File not found)\n"; return 0; }
	# Get to here, we have something to kill.
	my $pid = getprocessid();
	print "Stopping InspIRCd (pid: $pid)...\n";
	my $maxwait = (`ps -o command $pid` =~ /valgrind/i) ? 90 : 15;
	kill TERM => $pid or die "Cannot terminate IRCd: $!\n";
	for (1..$maxwait) {
		sleep 1;
		if (getstatus() == 0) {
			print "InspIRCd Stopped.\n";
			return;
		}
	}
	print "InspIRCd not dying quietly -- forcing kill\n";
	kill KILL => $pid;
	return 0;
}

###
# Generic Helper Functions.
###

# GetPidfile Version 2 - Now With Include Support..
# I beg for months for include support in insp, then..
# when it is added, it comes around and BITES ME IN THE ASS,
# because i then have to code support into this script.. Evil.

# Craig got bitten in the ass again --
# in 1.1 beta the include file is manditory, therefore
# if we cant find it, default to %conf%/inspircd.pid.
# Note, this also contains a fix for when the pid file is
# defined, but defined in a comment (line starts with #)
# -- Brain

my %filesparsed;

sub getpidfile
{
	my ($file) = @_;
	# Before we start, do we have a PID already? (Should never occur)
	if ($pid ne "") {
		return;
	}
	# Are We using a relative path?
	if ($file !~ /^\//) {
		# Convert it to a full path.
		$file = $runpath .'/'. $file;
	}

	# Have we checked this file before?
	return if $filesparsed{$file};
	$filesparsed{$file} = 1;

	# Open the File..
	open INFILE, '<', $file or return;
	# Grab entire file contents..
	my(@lines) = <INFILE>;
	# Close the file
	close INFILE;

	# remove trailing spaces
	chomp(@lines);
	for my $i (@lines) {
		# clean it up
		$i =~ s/[^=]+=\s(.*)/\1/;
		# Does this file have a pid?
		if (($i =~ /<pid file=\"(\S+)\">/i) && ($i !~ /^#/))
		{
			# Set the PID file and return.
			$pidfile = $1;
			if (-f $pidfile)
			{
				return;
			}
			elsif (-f "$runpath/$pidfile")
			{
				$pidfile = "$runpath/$pidfile";
				return;
			}
			return;
		}
	}


	# If we get here, NO PID FILE! -- Check for includes
	for my $i (@lines) {
		$i =~ s/[^=]+=\s(.*)/\1/;
		if (($i =~ s/\<include file=\"(.+?)\"\>//i) && ($i !~ /^#/))
		{
			# Decend into that file, and check for PIDs.. (that sounds like an STD ;/)
			getpidfile($1);
			# Was a PID found?
			if ($pidfile ne "") {
				# Yes, Return.
				return;
			}
		}
	}

	# End of includes / No includes found. Using default.
	$pidfile = $datadir . "/inspircd.pid";
}

sub getstatus {
	my $pid = getprocessid();
	return 0 if $pid == 0;
	return kill 0, $pid;
}


sub getprocessid {
	my $pid = 0;
	open PIDFILE, '<', $pidfile or return 0;
	while(<PIDFILE>)
	{
		/^(\d+)$/ and $pid = $1;
	}
	close PIDFILE;
	return $pid;
}

sub checkvalgrind
{
	unless(`valgrind --version`)
	{
		print "Couldn't start valgrind: $!\n";
		exit;
	}
}

sub checkgdb
{
	unless(`gdb --version`)
	{
		print "Couldn't start gdb: $!\n";
		exit;
	}
}

sub checkscreen
{
	unless(`screen --version`)
	{
		print "Couldn't start screen: $!\n";
		exit;
	}
}
