
# script_twiki_desc()
sub script_twiki_desc
{
return "TWiki";
}

sub script_twiki_uses
{
return ( "perl", "cgi", "apache" );
}

sub script_twiki_longdesc
{
return "TWiki is a flexible, powerful, and easy to use enterprise collaboration platform";
}

# script_twiki_versions()
sub script_twiki_versions
{
return ( "6.1.0" );
}

sub script_twiki_category
{
return "Wiki";
}

sub script_twiki_perl_modules
{
return ( "CGI::Session", "Net::SMTP", "Unicode::String" );
}

# script_twiki_depends(&domain, version, [&upgrade-info])
sub script_twiki_depends
{
local ($d, $ver, $sinfo) = @_;
if (!$sinfo) {
	local ($clash) = grep { $_->{'name'} eq 'twiki' }
			      &list_domain_scripts($d);
	$clash && return ("Only one instance of TWiki can be installed ".
			  "per virtual server");
	}
return ( );
}

# script_twiki_params(&domain, version, &upgrade-info)
# Returns HTML for table rows for options for installing PHP-NUKE
sub script_twiki_params
{
local ($d, $ver, $upgrade) = @_;
local $rv;
local $hdir = &public_html_dir($d, 1);
if ($upgrade) {
	# Options are fixed when upgrading
	local $dir = $upgrade->{'opts'}->{'dir'};
	$dir =~ s/^$d->{'home'}\///;
	$rv .= &ui_table_row("Install directory", $dir);
	}
else {
	# Show editable install options
	$rv .= &ui_table_row("Install sub-directory under <tt>$hdir</tt>",
			     &ui_opt_textbox("dir", &substitute_scriptname_template("twiki", $d), 30, "At top level"));
	}
return $rv;
}

# script_twiki_parse(&domain, version, &in, &upgrade-info)
# Returns either a hash ref of parsed options, or an error string
sub script_twiki_parse
{
local ($d, $ver, $in, $upgrade) = @_;
if ($upgrade) {
	# Options are always the same
	return $upgrade->{'opts'};
	}
else {
	local $hdir = &public_html_dir($d, 0);
	$in{'dir_def'} || $in{'dir'} =~ /\S/ && $in{'dir'} !~ /\.\./ ||
		return "Missing or invalid installation directory";
	local $dir = $in{'dir_def'} ? $hdir : "$hdir/$in{'dir'}";
	return { 'dir' => $dir,
		 'path' => $in{'dir_def'} ? "/" : "/$in{'dir'}", };
	}
}

# script_twiki_check(&domain, version, &opts, &upgrade-info)
# Returns an error message if a required option is missing or invalid
sub script_twiki_check
{
local ($d, $ver, $opts, $upgrade) = @_;
$opts->{'dir'} =~ /^\// || return "Missing or invalid install directory";
if (-r "$opts->{'dir'}/lib/TWiki.cfg") {
	return "TWiki appears to be already installed in the selected directory";
	}
local $cgidir = &cgi_bin_dir($d)."/twiki";
if (-d $cgidir) {
	return "TWiki appears to be already installed in the virtual server's cgi-bin directory";
	}
return undef;
}

# script_twiki_files(&domain, version, &opts, &upgrade-info)
# Returns a list of files needed by Twiki, each of which is a hash ref
# containing a name, filename and URL
sub script_twiki_files
{
local ($d, $ver, $opts, $upgrade) = @_;
local @files = ( { 'name' => "source",
	   'file' => "TWiki-$ver.tar.gz",
	   'url' => "http://twiki.org/p/pub/Codev/Release/TWiki-$ver.tgz" } );
return @files;
}

sub script_twiki_commands
{
return ("tar", "gunzip", "rcs", "diff");
}

# script_twiki_install(&domain, version, &opts, &files, &upgrade-info)
# Actually installs PhpWiki, and returns either 1 and an informational
# message, or 0 and an error
sub script_twiki_install
{
local ($d, $version, $opts, $files, $upgrade) = @_;
local ($out, $ex);

# Extract tar file to temp dir and copy to target
local $temp = &transname();
local $err = &extract_script_archive($files->{'source'}, $temp, $d,
                                     $opts->{'dir'}, "twiki");
$err && return (0, "Failed to extract source : $err");
local $cfile = "$opts->{'dir'}/lib/TWiki.cfg";

# Move the bin directory contents to cgi-bin
local $cgidir = &cgi_bin_dir($d)."/twiki";
$out = &run_as_domain_user($d, "mv ".quotemeta("$opts->{'dir'}/bin")." ".
				     quotemeta($cgidir));

# Edit the bin config file
local $bfile;
if (-r "$cgidir/LocalLib.cfg.txt") {
	# New version
	if (!-r "$cgidir/LocalLib.cfg") {
		&run_as_domain_user($d, "cp ".
			quotemeta("$cgidir/LocalLib.cfg.txt")." ".
			quotemeta("$cgidir/LocalLib.cfg"));
		}
	$bfile = "$cgidir/LocalLib.cfg";
	}
else {
	# Old version
	$bfile = "$cgidir/setlib.cfg";
	}
local $lref = &read_file_lines_as_domain_user($d, $bfile);
foreach my $l (@$lref) {
	if ($l =~ /^\s*\$twikiLibPath/) {
		$l = "\$twikiLibPath = '$opts->{'dir'}/lib';";
		}
	}
&flush_file_lines_as_domain_user($d, $bfile);

# Edit the lib config file
if (-r "$opts->{'dir'}/lib/LocalSite.cfg.txt" ||
    -r "$opts->{'dir'}/lib/TWiki.spec") {
	# New format for config file
	local $basecfile = -r "$opts->{'dir'}/lib/LocalSite.cfg.txt" ?
		"$opts->{'dir'}/lib/LocalSite.cfg.txt" :
		"$opts->{'dir'}/lib/TWiki.spec";
	if (!-r $cfile) {
		# Copy base into place
		&run_as_domain_user($d, "cp ".
			quotemeta($basecfile)." ".
			quotemeta("$opts->{'dir'}/lib/LocalSite.cfg"));
		$cfile = "$opts->{'dir'}/lib/LocalSite.cfg";
		}
	local $lref = &read_file_lines_as_domain_user($d, $cfile);
	local $fixed_locales;
	foreach my $l (@$lref) {
		if ($l =~ /^(#+\s*)?\$(TWiki::)?cfg\{DefaultUrlHost\}/) {
			$l = "\$$2cfg{DefaultUrlHost} = 'http://$d->{'dom'}';";
			}
		if ($l =~ /^(#+\s*)?\$(TWiki::)?cfg\{ScriptUrlPath\}/) {
			$l = "\$$2cfg{ScriptUrlPath} = '/cgi-bin/twiki';";
			}
		if ($l =~ /^(#+\s*)?\$(TWiki::)?cfg\{PubUrlPath\}/) {
			if ($opts->{'path'} eq '/') {
				$l = "\$$2cfg{PubUrlPath} = '/pub';";
				}
			else {
				$l = "\$$2cfg{PubUrlPath} =
					'$opts->{'path'}/pub';";
				}
			}
		if ($l =~ /^(#+\s*)?\$(TWiki::)?cfg\{PubDir\}/) {
			$l = "\$$2cfg{PubDir} = '$opts->{'dir'}/pub';";
			}
		if ($l =~ /^(#+\s*)?\$(TWiki::)?cfg\{TemplateDir}/) {
			$l = "\$$2cfg{TemplateDir} = '$opts->{'dir'}/templates';";
			}
		if ($l =~ /^(#+\s*)?\$(TWiki::)?cfg\{DataDir\}/) {
			$l = "\$$2cfg{DataDir} = '$opts->{'dir'}/data';";
			}
		if ($l =~ /^(#+\s*)?\$(TWiki::)?cfg\{WorkingDir\}/) {
			$l = "\$$2cfg{WorkingDir} = '$opts->{'dir'}/working';";
			}
		if ($l =~ /^(#+\s*)?\$(TWiki::)?cfg\{LocalesDir\}/) {
			$l = "\$$2cfg{LocalesDir} = '$opts->{'dir'}/locale';";
			$fixed_locales = 1;
			}
		if ($l =~ /^(#+\s*)?\$(TWiki::)?cfg\{TempfileDir\}/) {
			$l = "\$$2cfg{TempfileDir} = '$opts->{'dir'}/tmp';";
			}
		if ($l =~ /^(#+\s*)?\$(TWiki::)?cfg\{WebMasterEmail\}/) {
			$l = "\$$2cfg{WebMasterEmail} = '$d->{'emailto_addr'}';";
			}
		if ($l =~ /^(#+\s*)?\$(TWiki::)?cfg\{WebMasterName\}/) {
			local $qowner = &php_quotemeta($d->{'owner'}, 1);
			$l = "\$$2cfg{WebMasterName} = '$qowner';";
			}
		}
	if (!$fixed_locales) {
		# Needed but not set by default
		push(@$lref,
		     "\$TWiki::cfg{LocalesDir} = '$opts->{'dir'}/locale';");
		}
	&make_dir_as_domain_user($d, "$opts->{'dir'}/tmp", 0755);
	&make_file_php_writable($d, "$opts->{'dir'}/tmp");
	&flush_file_lines_as_domain_user($d, $cfile);
	}
else {
	# Old location
	$lref = &read_file_lines_as_domain_user($d, $cfile);
	foreach my $l (@$lref) {
		if ($l =~ /^\$defaultUrlHost/) {
			$l = "\$defaultUrlHost = 'http://$d->{'dom'}';";
			}
		if ($l =~ /^\$scriptUrlPath/) {
			$l = "\$scriptUrlPath = '/cgi-bin/twiki';";
			}
		if ($l =~ /^\$pubUrlPath/) {
			$l = "\$pubUrlPath = '$opts->{'path'}/pub';";
			}
		if ($l =~ /^\$pubDir/) {
			$l = "\$pubDir = '$opts->{'dir'}/pub';";
			}
		if ($l =~ /^\$templateDir/) {
			$l = "\$templateDir = '$opts->{'dir'}/templates';";
			}
		if ($l =~ /^\$dataDir/) {
			$l = "\$dataDir = '$opts->{'dir'}/data';";
			}
		}
	&flush_file_lines_as_domain_user($d, $cfile);
	}

# Hide data, lib and templates directories
foreach my $sd ("data", "lib", "templates", "working") {
	&run_as_domain_user($d, "cp ".quotemeta("$opts->{'dir'}/subdir-htaccess.txt")." ".quotemeta("$opts->{'dir'}/$sd"));
	}

# Make data and pub files writable
foreach my $sd ("data", "pub") {
	&make_file_php_writable($d, "$opts->{'dir'}/$sd");
	}

# Make the config file writable
&make_file_php_writable($d, $cfile);

# Setup a redirecting Apache config entry /twiki to /cgi-bin/twiki/view
&require_apache();
local $conf = &apache::get_config();
local @ports;
push(@ports, $d->{'web_port'}) if ($d->{'web'});
push(@ports, $d->{'web_sslport'}) if ($d->{'ssl'});
foreach my $port (@ports) {
	local ($virt, $vconf) = &get_apache_virtual($d->{'dom'}, $port);
	next if (!$virt);
	local $prot = $port eq $d->{'web_sslport'} ? "https" : "http";
	local @rm = &apache::find_directive("RedirectMatch", $vconf);
	local $redir = $opts->{'path'};
	$redir .= "/" if ($redir !~ /\/$/);
	push(@rm, "^$redir\$ $prot://$d->{'dom'}/cgi-bin/twiki/view");
	&apache::save_directive("RedirectMatch", \@rm, $vconf, $conf);
	&flush_file_lines($virt->{'file'});
	}
&register_post_action(\&restart_apache);

if (!$upgrade) {
	# Setup the Cron job to run the mailnotify program
	&foreign_require("cron", "cron-lib.pl");
	local $mailnotify = "$opts->{'dir'}/tools/mailnotify";
	local $perl = &get_perl_path();
	local $job = { 'user' => $d->{'user'},
		       'active' => 1,
		       'command' => "$perl -I $cgidir $mailnotify",
		       'mins' => 0,
		       'hours' => 0,
		       'days' => '*',
		       'months' => '*',
		       'weekdays' => '*' };
	&cron::create_cron_job($job);
	}

local $url = &script_path_url($d, $opts);
local $cgiurl = "http://$d->{'dom'}/cgi-bin/twiki/configure";
local $rp = $opts->{'dir'};
$rp =~ s/^$d->{'home'}\///;
return (1, "Initial TWiki installation complete. Go to <a target=_blank href='$cgiurl'>$cgiurl</a> to configure it.", "Under $rp", $url);
}

# script_twiki_uninstall(&domain, version, &opts)
# Un-installs a Twiki installation, by deleting the directory and database.
# Returns 1 on success and a message, or 0 on failure and an error
sub script_twiki_uninstall
{
local ($d, $version, $opts) = @_;

# Remove the contents of the target directory
local $derr = &delete_script_install_directory($d, $opts);
return (0, $derr) if ($derr);

# Remove the cgi-bin subdirectory
local $cgidir = &cgi_bin_dir($d)."/twiki";
&is_under_directory($d->{'home'}, $cgidir) ||
	return (0, "Invalid CGI directory $cgidir");
local $out = &backquote_logged("rm -rf ".quotemeta($cgidir)." 2>&1");
$? && return (0, "Failed to delete files : <tt>$out</tt>");

# Remove redirecting Apache config entry for /twiki
&require_apache();
local $conf = &apache::get_config();
local @ports;
push(@ports, $d->{'web_port'}) if ($d->{'web'});
push(@ports, $d->{'web_sslport'}) if ($d->{'ssl'});
foreach my $port (@ports) {
	local ($virt, $vconf) = &get_apache_virtual($d->{'dom'}, $port);
	next if (!$virt);
	local @rm = &apache::find_directive("RedirectMatch", $vconf);
	local @oldrm = @rm;
	@rm = grep { !/\/cgi-bin\/twiki\/view$/ } @rm;
	&apache::save_directive("RedirectMatch", \@rm, $vconf, $conf);
	if (scalar(@oldrm) != scalar(@rm)) {
		&flush_file_lines($virt->{'file'});
		}
	}
&register_post_action(\&restart_apache);

# Find and remove the Cron job
local $mailnotify = "$opts->{'dir'}/tools/mailnotify";
&foreign_require("cron", "cron-lib.pl");
local ($job) = grep { $_->{'user'} eq $d->{'user'} &&
		      $_->{'command'} =~ /\Q$mailnotify\E/ }
		    &cron::list_cron_jobs();
&cron::delete_cron_job($job) if ($job);

return (1, "TWiki directories deleted.");
}

# script_twiki_latest()
# Returns a URL and regular expression or callback func to get the version
sub script_twiki_latest
{
return ( "http://twiki.org/cgi-bin/view/Codev/DownloadTWiki",
	 "TWiki-([0-9\\.]+)\\.tgz" );
}

sub script_twiki_site
{
return 'http://twiki.org/';
}

1;

