
@mephisto_tables = (
	"assets",
	"assigned_sections",
	"cached_pages",
	"content_versions",
	"contents",
	"events",
	"memberships",
	"schema_info",
	"sections",
	"sessions",
	"sites",
	"taggings",
	"tags",
	"users"
	);

# script_mephisto_desc()
sub script_mephisto_desc
{
return "Mephisto";
}

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

sub script_mephisto_longdesc
{
return "Mephisto is a blog engine with some simple CMS-ish concepts (sections, pages) and a very flexible templating system";
}

# script_mephisto_versions()
sub script_mephisto_versions
{
return ( "0.7.3" );
}

sub script_mephisto_disabled
{
return 1;
}

sub script_mephisto_category
{
return "Blog";
}

sub script_mephisto_gems
{
return ( defined(&get_ruby_rails_gems) ? &get_ruby_rails_gems() : ( ),
	 [ "mongrel", undef, 1 ],
	 [ "rails", undef, 1 ],
	 [ "mysql", undef, 1 ] );
}

# script_mephisto_version(&domain, version, &opts)
# Returns the version of gem needed
sub script_mephisto_gem_version
{
return "1.3.1";		# For rails
}

# script_mephisto_depends(&domain, version)
# Check for ruby command, ruby gems, mod_proxy
sub script_mephisto_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, "Mephisto requires either MySQL database");
return @rv;
}

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

# script_mephisto_parse(&domain, version, &in, &upgrade-info)
# Returns either a hash ref of parsed options, or an error string
sub script_mephisto_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_mephisto_check(&domain, version, &opts, &upgrade-info)
# Returns an error message if a required option is missing or invalid
sub script_mephisto_check
{
local ($d, $ver, $opts, $upgrade) = @_;
if (-r "$opts->{'dir'}/config/database.yml") {
	return "Mephisto appears to be already installed in the selected directory";
	}
local ($dbtype, $dbname) = split(/_/, $opts->{'db'}, 2);
foreach my $t (@mephisto_tables) {
	local $clash = &find_database_table($dbtype, $dbname, $t);
	$clash && return "Mephisto appears to be already using the selected database (table $clash)";
	}
$opts->{'mongrels'} ||= 1;
return undef;
}

# script_mephisto_files(&domain, version, &opts, &upgrade-info)
# Returns a list of files needed by Mephisto, each of which is a hash ref
# containing a name, filename and URL
sub script_mephisto_files
{
local ($d, $ver, $opts, $upgrade) = @_;
local @files = ( { 'name' => "source",
	   'file' => "mephisto-$ver.tar.gz",
	   'url' => "http://s3.amazonaws.com/mephisto-blog/mephisto-$ver.tar.gz" } );
}

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

sub script_mephisto_packages
{
return &get_ruby_rails_packages();
}

# script_mephisto_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_mephisto_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);

if (!&find_rails_command("mongrel_rails")) {
	return (0, "The mongrel_rails command was not found");
	}

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

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

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 rails:update 2>&1 && ".
				       "rake db:bootstrap 2>&1");
	if ($?) {
		return (-1, "Database creation failed : <pre>$out</pre>");
		}
	}

# Create fix for Rails 2.3 bug
&create_mongrel_prefix_bugfix($d, $opts);

# 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);

	# In CSS file
	local $cssfile = "$opts->{'dir'}/public/stylesheets/mephisto/mephisto.css";
	local $lref = &read_file_lines_as_domain_user($d, $cssfile);
	local $path = $opts->{'path'};
	foreach my $l (@$lref) {
		$l =~ s/url\(\/images/url\(${path}\/images/g;
		}
	&flush_file_lines_as_domain_user($d, $cssfile);

	# In liquid.layout
	local $lqfile = "$opts->{'dir'}/themes/default/layouts/layout.liquid";
	local $lref = &read_file_lines_as_domain_user($d, $lqfile);
	foreach my $l (@$lref) {
		$l =~ s/<a\s+href="\/">/<a href="$path">/;
		$l =~ s/action="\/search"/action="$path\/search"/;
		}
	&flush_file_lines_as_domain_user($d, $lqfile);
	}

# 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, "mephisto", \@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, "mephisto-".$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."admin";
local $rp = $opts->{'dir'};
$rp =~ s/^$d->{'home'}\///;
return (1, "Mephisto installation complete. Go to <a target=_blank href='$adminurl'>$adminurl</a> to manage it.", "Under $rp using $dbtype database $dbname", $url, "admin", "test");
}

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

# Shut down the server process
&script_mephisto_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 /mephisto
&delete_mongrel_proxy($d, $opts->{'path'});

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

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

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

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

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

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

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

1;

