
@redmine_tables = (
	"attachments",
	"auth_sources",
	"boards",
	"changes",
	"changesets",
	"changesets_issues",
	"comments",
	"custom_fields",
	"custom_fields_projects",
	"custom_fields_trackers",
	"custom_values",
	"documents",
	"enabled_modules",
	"enumerations",
	"groups_users",
	"issue_categories",
	"issue_relations",
	"issue_statuses",
	"issues",
	"journal_details",
	"journals",
	"members",
	"member_roles",
	"messages",
	"news",
	"open_id_authentication_associations",
	"open_id_authentication_nonces",
	"plugin_schema_info",
	"projects",
	"projects_trackers",
	"queries",
	"repositories",
	"roles",
	"schema_migrations",
	"settings",
	"time_entries",
	"tokens",
	"trackers",
	"user_preferences",
	"users",
	"versions",
	"watchers",
	"wiki_content_versions",
	"wiki_contents",
	"wiki_pages",
	"wiki_redirects",
	"wikis",
	"workflows",
	"groups_users",
	"member_roles",
	"open_id_authentication_associations",
	"open_id_authentication_nonces",
	);

# script_redmine_desc()
sub script_redmine_desc
{
return "redmine";
}

sub script_redmine_uses
{
return ( "ruby", "proxy" );
}

sub script_redmine_author
{
return "Nick Orr";
}

sub script_redmine_disabled
{
return 1;	# Too hard to support dependencies
}

sub script_redmine_longdesc
{
return "Redmine is a flexible project management web application";
}

# script_redmine_versions()
sub script_redmine_versions
{
return ( "1.4.4", "1.1.3" );
}

sub script_redmine_release
{
return 1;
}

sub script_redmine_version_desc
{
local ($ver) = @_;
return $ver >= 2.1 ? "$ver (Experimental)" :
       $ver >= 1.4 ? "$ver (Stable)" :
		     "$ver (Old)";
}

sub script_redmine_category
{
return "Projects";
}

sub script_redmine_gems
{
local ($d, $ver) = @_;
if (defined(&get_ruby_rails_gems)) {
	my @gems = &get_ruby_rails_gems();
	foreach my $g (@gems) {
		if ($g->[0] eq 'rack') {
			$g->[1] = '1.0.1';
			}
		}
	push(@gems, [ "i18n", '0.4.2', 0 ]);
	if ($ver >= 1.4) {
		push(@gems, [ "bundler", undef, 0 ]);
		push(@gems, [ "mocha", "0.12.3", 0 ]);
		push(@gems, [ "jquery-rails", undef, 0 ]);
		push(@gems, [ "rmagick", undef, 0 ]);
		}
	return @gems;
	}
return ( );
}

# script_redmine_depends(&domain, version)
# Check for ruby command, ruby gems, mod_proxy
sub script_redmine_depends
{
local ($d, $ver) = @_;
local @rv;
&has_command("ruby") || push(@rv, "The ruby command is not installed");
&require_apache();
&has_proxy_balancer($d) ||
	push(@rv, "The Apache proxy module is not installed");
&has_domain_databases($d, [ "mysql" ]) ||
	push(@rv, "Redmine requires either MySQL database");
return @rv;
}

# script_redmine_params(&domain, version, &upgrade-info)
# Returns HTML for table rows for options for installing Redmine
sub script_redmine_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 redmine 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 redmine tables",
		     &ui_database_select("db", undef, \@dbs, $d, "redmine"));
	$rv .= &ui_table_row("Install sub-directory under <tt>$hdir</tt>",
			     &ui_opt_textbox("dir", &substitute_scriptname_template("redmine", $d), 30, "At top level"));
	$rv .= &show_mongrels_ports_input($d);
	}
return $rv;
}

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

# script_redmine_check(&domain, version, &opts, &upgrade-info)
# Returns an error message if a required option is missing or invalid
sub script_redmine_check
{
local ($d, $ver, $opts, $upgrade) = @_;
if (-r "$opts->{'dir'}/config/database.yml") {
	return "Redmine appears to be already installed in the selected directory";
	}
local ($dbtype, $dbname) = split(/_/, $opts->{'db'}, 2);
foreach my $t (@redmine_tables) {
	local $clash = &find_database_table($dbtype, $dbname, $t);
	$clash && return "redmine appears to be already using the selected database (table $clash)";
	}
$opts->{'mongrels'} ||= 1;
return undef;
}

# script_redmine_files(&domain, version, &opts, &upgrade-info)
# Returns a list of files needed by redmine, each of which is a hash ref
# containing a name, filename and URL
sub script_redmine_files
{
local ($d, $ver, $opts, $upgrade) = @_;
local %vmap = ( "1.4.4" => 76255,
		"2.1.2" => 76495,
	        "1.1.3" => 74722 );
local @files = ( { 'name' => "source",
	   'file' => "redmine-$ver.tar.gz",
	   'virtualmin' => 1,
	   'nocheck' => 1,
	   'url' => "http://rubyforge.org/frs/download.php/$vmap{$ver}/redmine-$ver.tar.gz" } );
}

sub script_redmine_commands
{
return ("ruby", "gcc", "make");
}

sub script_redmine_packages
{
return &get_ruby_rails_packages();
}

# script_redmine_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_redmine_install
{
local ($d, $version, $opts, $files, $upgrade) = @_;
local ($out, $ex);

# Check for the gem command (here instead of earlier, as it may have been
# automatically installed).
&has_command("gem") || return (0, "The Ruby gem command is not installed");

# Get database settings
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 = &mysql_user($d);
local $dbpass = &mysql_pass($d);
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);

# Install mongrel first, as we need it to run redmine
local $err = &install_ruby_gem("mongrel", undef, 1);
if ($err) {
	return (0, "Mongrel GEM install failed : <pre>$err</pre>");
	}
if (!&find_rails_command("mongrel_rails")) {
	return (0, "Mongrel appeared to install, but mongrel_rails command ".
		   "was not found");
	}

# Install Ruby on Rails
$err = &install_ruby_gem("rails", undef, 1);
if ($err) {
	return (0, "Rails on Rails install failed : <pre>$err</pre>");
	}

# Install Ruby mysql driver
$err = &install_ruby_gem("mysql", undef, 1);
if ($err) {
	return (0, "Rails MySQL driver install failed : <pre>$err</pre>");
	}

if ($upgrade) {
	# Stop the running redmine server
	&script_redmine_stop_server($d, $opts);
	}

if ($upgrade) {
	# Delete files from old version, which may not be compatible
	foreach my $dir ("app", "db", "doc", "extra", "lang", "lib",
			 "Rakefile", "script", "test", "vendor/gems",
			 "vendor/rails") {
		&unlink_file_as_domain_user($d, "$opts->{'dir'}/$dir");
		}

	# Move aside plugins, which may be broken, but only for a major update
	# like 0.8.6 -> 0.9.1
	local ($ver1, $ver2) = split(/\./, $version);
	local ($over1, $over2) = split(/\./, $upgrade->{'version'});
	if ($ver1 > $over1 || $ver2 > $over2) {
		&unlink_file_as_domain_user($d,
			"$opts->{'dir'}/vendor/plugins.old");
		&run_as_domain_user($d,
			"mv ".quotemeta("$opts->{'dir'}/vendor/plugins").
			" ".quotemeta("$opts->{'dir'}/vendor/plugins.old"));
		}
	}

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

# Generate the session store
$out = &run_as_domain_user($d, "cd ".quotemeta($opts->{'dir'})." && ".
		"rake config/initializers/session_store.rb 2>&1");
if ($?) {
	return (-1, "Session store failed : <pre>$out</pre>");
	}

if (!$upgrade) {
	# Find a free port
	$opts->{'port'} = &allocate_mongrel_port(undef, $opts->{'mongrels'});

	# Setup DB config
	local $cfile = "$opts->{'dir'}/config/database.yml";
	&open_tempfile_as_domain_user($d, CFILE, ">$cfile");
	&print_tempfile(CFILE,	"production:\n".
				"  adapter: mysql\n".
				"  database: $dbname\n".
				"  username: $dbuser\n".
				"  password: $dbpass\n".
				"  host: $dbhost\n");
	&print_tempfile(CFILE,	"development:\n".
				"  adapter: mysql\n".
				"  database: $dbname\n".
				"  username: $dbuser\n".
				"  password: $dbpass\n".
				"  host: $dbhost\n");
	&close_tempfile_as_domain_user($d, CFILE);

	# Run the DB creation script
	$out = &run_as_domain_user($d, "cd ".quotemeta($opts->{'dir'})." && ".
			       "rake db:migrate RAILS_ENV=production 2>&1");
	if ($?) {
		return (-1, "Database creation failed : <pre>$out</pre>");
		}

	# Create email config
	local $efile = "$opts->{'dir'}/config/email.yml";
	&open_tempfile_as_domain_user($d, CFILE, ">$efile");
	&print_tempfile(CFILE,  "production:\n".
				"  delivery_method: :smtp\n".
				"  smtp_settings:\n".
				"    address: localhost\n".
				"    port: 25\n".
				"    domain: $d->{'dom'}\n".
				"\n");
	&print_tempfile(CFILE,  "development:\n".
				"  delivery_method: :smtp\n".
				"  smtp_settings:\n".
				"    address: localhost\n".
				"    port: 25\n".
				"    domain: $d->{'dom'}\n".
				"\n");
	&close_tempfile_as_domain_user($d, CFILE);
	}
else {
	# Update the DB
	&run_as_domain_user($d,
	  "cd ".quotemeta($opts->{'dir'})." && ".
	  "rake db:migrate RAILS_ENV=production 2>&1");

	# Update plugins
	&run_as_domain_user($d,
	 "cd ".quotemeta($opts->{'dir'})." && ".
	 "rake db:migrate:upgrade_plugin_migrations RAILS_ENV=production 2>&1");
	&run_as_domain_user($d,
	 "cd ".quotemeta($opts->{'dir'})." && ".
	 "rake db:migrate_plugins RAILS_ENV=production  2>&1");

	# Delete old session files
	&run_as_domain_user($d,
	  "cd ".quotemeta($opts->{'dir'})." && ".
	  "rake tmp:cache:clear");
	&run_as_domain_user($d,
	  "cd ".quotemeta($opts->{'dir'})." && ".
	  "rake tmp:sessions:clear");
	}

# Fix up URL base
if ($opts->{'path'} ne '/') {
	# In config file
	local $efile = "$opts->{'dir'}/config/environment.rb";
	local $lref = &read_file_lines_as_domain_user($d, $efile);
	foreach my $l (@$lref) {
		if ($l =~ /^#*\s*ActionController::AbstractRequest.relative_url_root/) {
			$l = "ActionController::AbstractRequest.relative_url_root = '$opts->{'path'}'";
			}
		}
	&flush_file_lines_as_domain_user($d, $efile);

	# Add neeed file to fix missing function
	local $ffile = "$opts->{'dir'}/config/initializers/00-fix-mongrel.rb";
	&open_tempfile_as_domain_user($d, FFILE, ">$ffile");
	&print_tempfile(FFILE, <<EOF
module ActionController
  class AbstractRequest < ActionController::Request
    def self.relative_url_root=(path)
      ActionController::Base.relative_url_root=(path)
    end
    def self.relative_url_root
      ActionController::Base.relative_url_root
    end
  end
end
EOF
	);
	&close_tempfile_as_domain_user($d, FFILE);
	}

# Create log dir if missing, for mongrel
local $logdir = "$opts->{'dir'}/log";
if (!-d $logdir) {
	&make_dir_as_domain_user($d, $logdir, 0700);
	}

# Start the servers
local (@logs, @startcmds, @stopcmds);
local @ports = split(/\s+/, $opts->{'port'});
local $err = &mongrel_rails_start_servers($d, $opts, "redmine", \@startcmds,
					  \@stopcmds, \@logs);
return (0, $err) if ($err);
$opts->{'log'} = join(" ", @logs);

# Setup an Apache proxy for it
&setup_mongrel_proxy($d, $opts->{'path'}, $opts->{'port'},
		     $opts->{'path'} eq '/' ? undef : $opts->{'path'});

if (!$upgrade) {
	# Configure server to start at boot
	&setup_mongrel_startup($d,
			       join("\n", @startcmds),
			       join("\n", @stopcmds),
			       $opts,
			       1, "redmine-".$ports[0], "Mephisto Wiki");
	}

if (!$upgrade) {
	# Deny regular web access to directory
	&protect_rails_directory($d, $opts);
	}

local $url = &script_path_url($d, $opts);
local $adminurl = $url."login";
local $rp = $opts->{'dir'};
$rp =~ s/^$d->{'home'}\///;
return (1, "redmine installation complete. Go to <a target=_blank href='$adminurl'>$adminurl</a> to manage it.<br />
            ", "Under $rp using $dbtype database $dbname", $url, "admin", "admin");
}

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

# Shut down the server process
&script_redmine_stop_server($d, $opts);

# Remove bootup script
&delete_mongrel_startup($d, $opts, "mongrel_rails start", $opts->{'port'});

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

# Remove proxy Apache config entry for /redmine
&delete_mongrel_proxy($d, $opts->{'path'});

# Remove all redmine tables from the database
&cleanup_script_database($d, $opts->{'db'}, \@redmine_tables);

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

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

# script_redmine_stop(&domain, &sinfo)
# Stop running mongrel process
sub script_redmine_stop
{
local ($d, $sinfo) = @_;
&script_redmine_stop_server($d, $sinfo->{'opts'});
&delete_mongrel_startup($d, $sinfo->{'opts'},
			"mongrel_rails start", $sinfo->{'opts'}->{'port'});
}

# Disabled, as newer versions are too hard to support
#sub script_redmine_latest
#{
#local ($ver) = @_;
#return ( "http://rubyforge.org/frs/?group_id=1850",
#         $ver >= 2.1 ? "redmine-([0-9\\.]+)\\.tar\\.gz" :
#	 $ver >= 1.4 ? "redmine-(1\\.[0-9\\.]+)\\.tar\\.gz" :
#		       "redmine-(1\\.1\\.[0-9\\.]+)\\.tar\\.gz" );
#}

sub script_redmine_start_server
{
local ($d, $opts) = @_;
return &mongrel_rails_start_servers($d, $opts, "redmine");
}

sub script_redmine_status_server
{
local ($d, $opts) = @_;
return &mongrel_rails_status_servers($d, $opts);
}

# script_redmine_stop_server(&domain, &opts)
# Stop an redmine webserver
sub script_redmine_stop_server
{
local ($d, $opts) = @_;
&mongrel_rails_stop_servers($d, $opts);
}

sub script_redmine_site
{
return 'http://www.redmine.org/';
}

1;

