#!/usr/bin/perl -w
#
#	Copyright (c) 2006 Krzysztof Krzyzaniak
#
#	Contains changes from:
#		- Tobias Gruetzmacher <tobias@portfolio16.de>
#
#	You may distribute under the terms of either the GNU General Public
#	License[1] or the Artistic License[2].
#
#	[1] http://www.gnu.org/licenses/gpl.html
#	[2] http://www.perl.com/pub/a/language/misc/Artistic.html
#

use strict;
use Term::ReadLine;
use File::Basename;
use File::Glob ':glob';
use File::stat;

#--- some initializations
my $confdir = "/etc/lighttpd/";
my %available = ();
my %enabled = ();
my @todo = ();

my %moduledeps = ();

my $enabling = 1;


#--- first check if we enabling or disabling
if ($0 =~ /disable-mod$/) {
	#--- disabling mode
	$enabling = 0;
}

#--- list of available modules
my @files = bsd_glob($confdir.'conf-available/*.conf');
print "Available modules: ";
foreach my $file (@files) {
	if (basename($file) =~ /^\d+\-([\w\-\.]+)\.conf$/) {
		$available{$1} = $file;
		print qq{$1 };
	}
}
print "\n";

#--- list of already enabled modules
@files = bsd_glob($confdir.'conf-enabled/*.conf');
print "Already enabled modules: ";
foreach my $file (@files) {
	if (basename($file) =~ /^\d+\-([\w\-\.]+)\.conf$/) {
		$enabled{$1} = $file;
		print qq{$1 };
	}
}
print "\n";

unless (defined($ARGV[0])) {
	my $prompt =  $enabling ? 'Enable module: ' : 'Disable module: ';
	my $term = new Term::ReadLine $prompt;
	my $OUT = $term->OUT || \*STDOUT;
	my $var = lc($term->readline($prompt));
	@todo = split(/ /, $var);
}
else {
	@todo = @ARGV;
}


#--- activate (link) or deactivate (remove) module
foreach my $do (@todo) {


	if ($enabling) {
		next unless defined($available{$do});
		my $target = sprintf("%s/conf-enabled/%s", $confdir,basename($available{$do}));
		print qq{Enabling $do: };

		my $st = stat($target);
		unless ( -f $target ) {
			if (symlink($available{$do}, $target)) {
				print "ok\n";
			}
			else {
				print "failure: $!\n";
			}
		}
		else {
			print "already enabled\n";
		}

		#--- check dependencies
		for my $module (@{$moduledeps{$do}})
		{
			unless ( -f $target && -l $target )
			{
				print qq{Module $do depends on module $module which is not activated.\n};
			}
		}
	}
	else {
		if (defined($enabled{$do})) {
			print qq{Disabling $do\n};
			my $target = sprintf("%s/conf-enabled/%s", $confdir,basename($enabled{$do}));
			unlink($target);
		} else {
			print qq{Already disabled $do\n};
		}
	}
}

print "Run /etc/init.d/lighttpd force-reload to enable changes\n";
