
@bugzilla_tables = (
	"attach_data",
	"attachments",
	"bug_group_map",
	"bug_severity",
	"bug_status",
	"bugs",
	"bugs_activity",
	"bugs_fulltext",
	"bz_schema",
	"category_group_map",
	"cc",
	"classifications",
	"component_cc",
	"components",
	"dependencies",
	"duplicates",
	"email_setting",
	"fielddefs",
	"flagexclusions",
	"flaginclusions",
	"flags",
	"flagtypes",
	"group_control_map",
	"group_group_map",
	"groups",
	"keyworddefs",
	"keywords",
	"logincookies",
	"longdescs",
	"milestones",
	"namedqueries",
	"namedqueries_link_in_footer",
	"namedquery_group_map",
	"op_sys",
	"priority",
	"products",
	"profile_setting",
	"profiles",
	"profiles_activity",
	"quips",
	"rep_platform",
	"resolution",
	"series",
	"series_categories",
	"series_data",
	"setting",
	"setting_value",
	"status_workflow",
	"tokens",
	"user_group_map",
	"versions",
	"votes",
	"watch",
	"whine_events",
	"whine_queries",
	"whine_schedules",
	);

# script_bugzilla_desc()
sub script_bugzilla_desc
{
return "Bugzilla";
}

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

sub script_bugzilla_longdesc
{
return "Bugzilla is server software designed to help you manage software development";
}

# script_bugzilla_versions()
sub script_bugzilla_versions
{
return ( "5.1.2" );
}

sub script_bugzilla_release
{
return 3;		# To fix download URL
}

sub script_bugzilla_category
{
return "Tracker";
}

sub script_bugzilla_perl_modules
{
return ( "Email::Sender", "Template::Toolkit", "Date::Format",
	 "CGI", "DBI", "File::Spec", "DBD::mysql", "Digest::SHA",
	 "DateTime", "DateTime::TimeZone", "Email::MIME",
	 "List::MoreUtils", "File::Slurp", "JSON::XS", "Test::Taint",
	 "DBD::SQLite" );
}

sub script_bugzilla_dbs
{
return ("mysql");
}

# script_bugzilla_params(&domain, version, &upgrade-info)
# Returns HTML for table rows for options for installing PHP-NUKE
sub script_bugzilla_params
{
local ($d, $ver, $upgrade) = @_;
local $rv;
local $hdir = &public_html_dir($d, 1);
if ($upgrade) {
	# Options are fixed when upgrading
	local ($dbtype, $dbname) = split(/_/, $upgrade->{'opts'}->{'db'}, 2);
	$rv .= &ui_table_row("Database for Bugzilla tables", $dbname);
	local $dir = $upgrade->{'opts'}->{'dir'};
	$dir =~ s/^$d->{'home'}\///;
	$rv .= &ui_table_row("Install directory", $dir);
	}
else {
	# Show editable install options
	local @dbs = &domain_databases($d, [ "mysql" ]);
	$rv .= &ui_table_row("Database for Bugzilla tables",
		     &ui_database_select("db", undef, \@dbs, $d, "bugzilla"));
	$rv .= &ui_table_row("Install sub-directory under <tt>$hdir</tt>",
			     &ui_opt_textbox("dir", &substitute_scriptname_template("bugzilla", $d), 30, "At top level"));
	}
return $rv;
}

# script_bugzilla_parse(&domain, version, &in, &upgrade-info)
# Returns either a hash ref of parsed options, or an error string
sub script_bugzilla_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'}";
	local ($newdb) = ($in->{'db'} =~ s/^\*//);
	return { 'db' => $in->{'db'},
		 'newdb' => $newdb,
	         'dir' => $dir,
		 'path' => $in{'dir_def'} ? "/" : "/$in{'dir'}", };
	}
}

# script_bugzilla_check(&domain, version, &opts, &upgrade-info)
# Returns an error message if a required option is missing or invalid
sub script_bugzilla_check
{
local ($d, $ver, $opts, $upgrade) = @_;
$opts->{'dir'} =~ /^\// || return "Missing or invalid install directory";
if (-r "$opts->{'dir'}/index.cgi") {
	return "Bugzilla appears to be already installed in the selected directory";
	}
local ($dbtype, $dbname) = split(/_/, $opts->{'db'}, 2);
foreach my $t (@bugzilla_tables) {
	local $clash = &find_database_table($dbtype, $dbname, $t);
	$clash && return "Bugzilla appears to be already using the selected database (table $clash)";
	}
return undef;
}

# script_bugzilla_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_bugzilla_files
{
local ($d, $ver, $opts, $upgrade) = @_;
local @files = ( { 'name' => "source",
	   'file' => "bugzilla-$ver.tar.gz",
	   'url' => "http://ftp.mozilla.org/pub/mozilla.org/webtools/bugzilla-$ver.tar.gz" } );
return @files;
}

sub script_bugzilla_commands
{
return ("tar", "gunzip");
}

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

# Setup DB
if ($opts->{'newdb'} && !$upgrade) {
	local $err = &create_script_database($d, $opts->{'db'});
	return (0, "Database creation failed : $err") if ($err);
	}
local ($dbtype, $dbname) = split(/_/, $opts->{'db'}, 2);
local $dbuser = $dbtype eq "mysql" ? &mysql_user($d) : &postgres_user($d);
local $dbpass = $dbtype eq "mysql" ? &mysql_pass($d) : &postgres_pass($d, 1);
local $dbphptype = $dbtype eq "mysql" ? "mysql" : "psql";
local $dbhost = &get_database_host($dbtype, $d);
local $dberr = &check_script_db_connection($dbtype, $dbname, $dbuser, $dbpass);
return (0, "Database connection failed : $dberr") if ($dberr);

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

local $cfile = "$opts->{'dir'}/localconfig";
if (!-r $cfile) {
	# Run checksetup.pl once, to create localconfig
	&clean_environment();
	$out = &run_as_domain_user($d, "cd ".quotemeta($opts->{'dir'}).
				       " && ./checksetup.pl");
	&reset_environment();
	if ($? || $out !~ /Reading.*localconfig/i) {
		# Something was wrong!
		&delete_script_install_directory($d, $opts);
		return (0, "Bugzilla dependency problems detected :\n".
		           "<pre>".&html_escape($out)."</pre>");
		}
	}

# Remove stupid mysql version blacklist
local $blfile = "$opts->{'dir'}/Bugzilla/Constants.pm";
local $lref = &read_file_lines_as_domain_user($d, $blfile);
foreach my $l (@$lref) {
	if ($l =~ /^\s+blacklist.*3/) {
		$l = "";
		}
	}
&flush_file_lines_as_domain_user($d, $blfile);

if (!$upgrade) {
	# Edit localconfig
	local $lref = &read_file_lines_as_domain_user($d, $cfile);
	local $mode = &get_domain_php_mode($d);
	foreach my $l (@$lref) {
		if ($l =~ /^\$webservergroup\s*=/) {
			if ($mode eq "mod_php") {
				# Running as Apache
				local @uinfo = getpwnam(&get_apache_user($d));
				local $g = getgrgid($uinfo[3]);
				$l = "\$webservergroup = '$g';";
				}
			else {
				# As domain owner
				$l = "\$webservergroup = '$d->{'group'}';";
				}
			}
		if ($l =~ /^\$db_host\s*=/) {
			$l = "\$db_host = '$dbhost';";
			}
		if ($l =~ /^\$db_name\s*=/) {
			$l = "\$db_name = '$dbname';";
			}
		if ($l =~ /^\$db_user\s*=/) {
			$l = "\$db_user = '$dbuser';";
			}
		if ($l =~ /^\$db_pass\s*=/) {
			$l = "\$db_pass = '".&php_quotemeta($dbpass, 1)."';";
			}
		}
	&flush_file_lines_as_domain_user($d, $cfile);

	# Re-run checksetup.pl, to check for Perl modules again
	&clean_environment();
	$out = &run_as_domain_user($d, "cd ".quotemeta($opts->{'dir'}).
				       " && ./checksetup.pl --check-modules");
	&reset_environment();
	if ($?) {
		&delete_script_install_directory($d, $opts);
		return (0, "Bugzilla dependency problems detected :\n".
		           "<pre>".&html_escape($out)."</pre>");
		}

	# Run checksetup.pl again
	if (length($dompass) < 6) {
		$dompass .= "123456";
		}
	&clean_environment();
	local $cin = &transname();
	open(CIN, ">$cin");
	print CIN $d->{'emailto_addr'},"\n";
	print CIN $d->{'owner'},"\n";
	print CIN $dompass,"\n";
	print CIN $dompass,"\n";
	close(CIN);
	&set_ownership_permissions($d->{'uid'}, $d->{'gid'}, undef, $cin);
	$out = &run_as_domain_user($d, "cd ".quotemeta($opts->{'dir'}).
				       " && ./checksetup.pl <$cin");
	&reset_environment();
	}

# Add a directory block for the bugzilla dir, with CGIs enabled for .cgi
&require_apache();
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, $conf) = &get_apache_virtual($d->{'dom'}, $port);
	next if (!$virt);
	local @dirs = &apache::find_directive_struct("Directory", $vconf);
	local ($bz) = grep { $_->{'words'}->[0] eq $opts->{'dir'} } @dirs;
	if (!$bz) {
		# Create new directory block
		local $lref = &read_file_lines($virt->{'file'});
		splice(@$lref, $virt->{'eline'}, 0,
		       "<Directory $opts->{'dir'}>",
		       "Options +ExecCGI",
		       "AllowOverride Limit",
		       "DirectoryIndex index.cgi",
		       "AddHandler cgi-script .cgi",
		       "</Directory>");
		&flush_file_lines($virt->{'file'});
		undef(@apache::get_config_cache);
		}
	else {
		# Add required directives to existing Directory block
		local $bconf = $bz->{'members'};
		local @opts = &apache::find_directive("Options", $bconf);
		if (!@opts || $opts[0] !~ /ExecCGI/) {
			if (@opts) { $opts[0] .= " +ExecCGI"; }
			else { @opts = ( "+ExecCGI" ); }
			&apache::save_directive("Options", \@opts,
						$bconf, $conf);
			}
		local @index = &apache::find_directive("DirectoryIndex",
						       $bconf);
		if (!@index || $index[0] !~ /index.cgi/) {
			if (@index) { $index[0] .= " index.cgi"; }
			else { @index = ( "index.cgi" ); }
			&apache::save_directive("DirectoryIndex", \@index,
						$bconf, $conf);
			}
		local @handler = &apache::find_directive("AddHandler", $bconf);
		local ($cgih) = grep { /cgi-script\s+.cgi/ } @handler;
		if (!$cgih) {
			push(@handler, "cgi-script .cgi");
			&apache::save_directive("AddHandler", \@handler,
						$bconf, $conf);
			}
		&flush_file_lines($virt->{'file'});
		}
	}
&register_post_action(\&restart_apache);

local $url = &script_path_url($d, $opts);
local $rp = $opts->{'dir'};
$rp =~ s/^$d->{'home'}\///;
return (1, "Initial Bugzilla installation complete. Go to <a target=_blank href='$url'>$url</a> to use it.", "Under $rp", $url, $d->{'emailto_addr'}, $dompass);
}

# script_bugzilla_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_bugzilla_uninstall
{
local ($d, $version, $opts) = @_;

# Remove bugzilla tables from the database
local $tries;
while(!$done && $tries++ < @bugzilla_tables) {
	local $err = &cleanup_script_database(
		$d, $opts->{'db'}, \@bugzilla_tables);
	last if (!$err);
	}

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

# Remove Apache directory entry for the dir, unless installed at the root
if ($opts->{'dir'} ne &public_html_dir($d)) {
	&require_apache();
	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 @dirs = &apache::find_directive_struct("Directory",
							     $vconf);
		local ($bz) = grep { $_->{'words'}->[0] eq $opts->{'dir'} }
				   @dirs;
		if ($bz) {
			local $lref = &read_file_lines($bz->{'file'});
			splice(@$lref, $bz->{'line'},
			       $bz->{'eline'}-$bz->{'line'}+1);
			&flush_file_lines($virt->{'file'});
			undef(@apache::get_config_cache);
			}
		}
	&register_post_action(\&restart_apache);
	}

# Take out the DB
if ($opts->{'newdb'}) {
	&delete_script_database($d, $opts->{'db'});
	}

return (1, "Bugzilla directory and tables deleted.");
}

# script_bugzilla_latest()
# Returns a URL and regular expression or callback func to get the version
#sub script_bugzilla_latest
#{
#return ( "http://ftp.mozilla.org/pub/mozilla.org/webtools/",
#	 "bugzilla-(3\\.6\\.[0-9\\.]+).tar.gz" );
#}

sub script_bugzilla_site
{
return 'http://www.bugzilla.org/';
}

sub script_bugzilla_passmode
{
return 2;
}

1;

