
@typo_tables = (
	"articles_tags",
	"blacklist_patterns",
	"blogs",
	"cache_informations",
	"categories",
	"categorizations",
	"contents",
	"feedback",
	"notifications",
	"page_caches",
	"pings",
	"profiles",
	"profiles_rights",
	"redirects",
	"resources",
	"rights",
	"schema_migrations",
	"sessions",
	"sidebars",
	"sitealizer",
	"tags",
	"text_filters",
	"triggers",
	"users",
	);

# script_typo_desc()
sub script_typo_desc
{
return "Typo";
}

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

sub script_typo_longdesc
{
return "Typo is a lean engine that makes blogging easy";
}

# script_typo_versions()
sub script_typo_versions
{
return ( "5.5" );
}

sub script_typo_category
{
return "Blog";
}

sub script_typo_gems
{
local ($d, $ver, $opts) = @_;
return ( defined(&get_ruby_rails_gems) ? &get_ruby_rails_gems() : ( ),
	 [ "mongrel", undef, 1 ],
	 [ "typo", $ver ],
	 [ "mysql", undef, 1 ], );
}

# script_typo_depends(&domain, version)
# Check for ruby command, ruby gems, mod_proxy
sub script_typo_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");
return @rv;
}

# script_typo_params(&domain, version, &upgrade-info)
# Returns HTML for table rows for options for installing PHP-NUKE
sub script_typo_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
	local @dbs = &domain_databases($d, [ "mysql" ]);
	$rv .= &ui_table_row("Database for Typo tables",
		     &ui_database_select("db", undef, \@dbs, $d, "typo"));
	$rv .= &ui_table_row("Install sub-directory under <tt>$hdir</tt>",
			     &ui_opt_textbox("dir", &substitute_scriptname_template("typo", $d), 30, "At top level"));
	}
return $rv;
}

# script_typo_parse(&domain, version, &in, &upgrade-info)
# Returns either a hash ref of parsed options, or an error string
sub script_typo_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_typo_check(&domain, version, &opts, &upgrade-info)
# Returns an error message if a required option is missing or invalid
sub script_typo_check
{
local ($d, $ver, $opts, $upgrade) = @_;
$opts->{'dir'} =~ /^\// || return "Missing or invalid install directory";
$opts->{'db'} || return "Missing database";
if (-r "$opts->{'dir'}/installer/rails_installer.yml") {
	return "Typo appears to be already installed in the selected directory";
	}
local ($dbtype, $dbname) = split(/_/, $opts->{'db'}, 2);
foreach my $t (@typo_tables) {
	local $clash = &find_database_table($dbtype, $dbname, $t);
	$clash && return "Typo appears to be already using the selected database (table $clash)";
	}
return undef;
}

# script_typo_files(&domain, version, &opts, &upgrade-info)
# Returns a list of files needed by Typo, each of which is a hash ref
# containing a name, filename and URL
sub script_typo_files
{
local ($d, $ver, $opts, $upgrade) = @_;
return ( );	# Nothing, as everything is downloaded
}

sub script_typo_commands
{
return ("ruby");
}

sub script_typo_packages
{
return &get_ruby_rails_packages();
}

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

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

# 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");
local $typo = &find_rails_command("typo");
if (!$typo) {
	return (0, "The <tt>typo</tt> command could not be found");
	}

# Create target dir
if (!-d $opts->{'dir'}) {
	$out = &run_as_domain_user($d, "mkdir -p ".quotemeta($opts->{'dir'}));
	-d $opts->{'dir'} ||
		return (0, "Failed to create directory : <tt>$out</tt>.");
	}

# Create the database config file
if (!$upgrade) {
	local $cfile = "$opts->{'dir'}/config/database.yml";
	&make_dir_as_domain_user($d, "$opts->{'dir'}/config", 0755);
	&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);
	}

# As the domain owner, run the typo command to setup files. This will
# start the server automatically.
$out = &run_as_domain_user($d, "cd ".quotemeta($opts->{'dir'})." && ".
			       "$typo install . 2>&1");
if ($? && $out !~ /is\s+now\s+running/i) {
	return (-1, "Typo setup failed : <pre>$out</pre>");
	}

# If typo is running, kill it so we can start on out own port. Sadly it doesn't
# seem to write a PID file the first time!
&foreign_require("proc", "proc-lib.pl");
local @procs = &proc::list_processes();
local @servers = grep { ($_->{'user'} eq $d->{'user'} ||
			 $_->{'user'} eq $d->{'uid'}) &&
			$_->{'args'} =~ /start\s+\Q$opts->{'dir'}\E/ } @procs;
foreach my $s (@servers) {
	kill('KILL', $s->{'pid'});
	}

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

	# Put the port into the .yml config
	local $yml = "$opts->{'dir'}/installer/rails_installer.yml";
	local $lref = &read_file_lines_as_domain_user($d, $yml);
	local $fixed_prefix;
	foreach my $l (@$lref) {
		if ($l =~ /^\s*port-number:\s*/) {
			$l = "port-number: $opts->{'port'}";
			}
		elsif ($l =~ /^\s*url-prefix:\s*/ && $opts->{'path'} ne '/') {
			$l = "url-prefix: $opts->{'path'}";
			$fixed_prefix = 1;
			}
		}
	if (!$fixed_prefix && $opts->{'path'} ne '/') {
		push(@$lref, "url-prefix: $opts->{'path'}");
		}
	&flush_file_lines_as_domain_user($d, $yml);
	}

# Start the server
$out = &run_as_domain_user($d, "cd ".quotemeta($opts->{'dir'})." && ".
			       "$typo start . 2>&1");
if ($?) {
	return (-1, "Failed to start Typo server : <pre>$out</pre>");
	}

# 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
	local $startcmd = "cd ".quotemeta($opts->{'dir'})."; ".
                          "$typo start . 2>&1 </dev/null";
	local $stopcmd = "kill `cat ".quotemeta($pidfile)."`";
	&setup_mongrel_startup($d, $startcmd, $stopcmd, $opts,
			       1, "typo-".$opts->{'port'}, "Typo Blog Engine");
	}

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

local $url = &script_path_url($d, $opts);
local $rp = $opts->{'dir'};
$rp =~ s/^$d->{'home'}\///;
return (1, "Initial Typo installation complete. Go to <a target=_blank href='$url'>$url</a> to create your login and blog.", "Under $rp", $url);
}

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

# Shut down the server process
local $pidfile = "$opts->{'dir'}/tmp/pid.txt";
local $pid = &check_pid_file($pidfile);
if ($pid) {
	kill('KILL', $pid);
	}

# Remove bootup script
local $typo = &find_rails_command("typo");
&delete_mongrel_startup($d, $opts, "$typo start .");
&delete_mongrel_startup($d, $opts, "typo start .");

# 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 /typo
&delete_mongrel_proxy($d, $opts->{'path'});
&register_post_action(\&restart_apache);

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

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

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

# script_typo_start_server(&domain, &opts)
# Start the Typoe server process
sub script_typo_start_server
{
local ($d, $opts) = @_;
local $typo = &find_rails_command("typo");
local $out = &run_as_domain_user($d, "cd ".quotemeta($opts->{'dir'})." && ".
			       	     "$typo start . 2>&1");
return $? ? "<tt>".&html_escape($out)."</tt>" : undef;
}

# script_typo_status_server(&domain, &opts)
# Returns the PID of the Typo server process
sub script_typo_status_server
{
local ($d, $opts) = @_;
local $pidfile = "$opts->{'dir'}/tmp/pid.txt";
local $pid = &check_pid_file($pidfile);
return $pid ? ( $pid ) : ( );
}

# script_typo_stop_server(&domain, &opts)
# Stop the running Typo server process
sub script_typo_stop_server
{
local ($d, $opts) = @_;
local $pidfile = "$opts->{'dir'}/tmp/pid.txt";
local $pid = &check_pid_file($pidfile);
if ($pid) {
	unlink($pidfile);
	return kill('KILL', $pid);
	}
return 0;
}

# script_typo_stop(&domain, &sinfo)
# Stop running mongrel process
sub script_typo_stop
{
local ($d, $sinfo) = @_;
&script_typo_stop_server($d, $sinfo->{'opts'});
local $typo = &find_rails_command("typo");
&delete_mongrel_startup($d, $sinfo->{'opts'}, "$typo start .");
&delete_mongrel_startup($d, $sinfo->{'opts'}, "typo start .");
}

sub script_typo_check_latest
{
local ($ver) = @_;
foreach my $nv (&ruby_gem_versions("typo")) {
	return $nv if (&compare_versions($nv, $ver) > 0 &&
		       $nv !~ /^\d+\.\d+\.\d+$/);
	}
return undef;
}

sub script_typo_site
{
return 'http://typosphere.org/';
}

sub script_typo_disabled
{
return 1;
}

1;

