
@radiant_tables = (
	"config",
	"extension_meta",
	"layouts",
	"page_parts",
	"pages",
	"schema_info",
	"snippets",
	"users",
	"sessions",
	"schema_migrations",
	);

# script_radiant_desc()
sub script_radiant_desc
{
return "Radiant CMS";
}

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

sub script_radiant_longdesc
{
return "Radiant is a no-fluff, open source content management system designed for small teams";
}

# script_radiant_versions()
sub script_radiant_versions
{
return ( "1.1.4" );
}

sub script_radiant_category
{
return "CMS";
}

sub script_radiant_dbs
{
return ("mysql");
}

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

# script_radiant_depends(&domain, version)
# Check for ruby command, ruby gems, mod_proxy
sub script_radiant_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_radiant_params(&domain, version, &upgrade-info)
# Returns HTML for table rows for options for installing PHP-NUKE
sub script_radiant_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 Radiant CMS 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 Radiant CMS tables",
		     &ui_database_select("db", undef, \@dbs, $d, "radiant"));
	$rv .= &ui_table_row("Install sub-directory under <tt>$hdir</tt>",
			     &ui_opt_textbox("dir", undef, 30,
					     "At top level"));
	$rv .= &ui_table_row("",
	    "Warning - Radiant's web pages will not currently be displayed ".
	    "properly unless it is installed at the top level.");
	$rv .= &show_mongrels_ports_input($d);
	}
return $rv;
}

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

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

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

sub script_radiant_packages
{
return &get_ruby_rails_packages();
}

# script_radiant_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_radiant_install
{
local ($d, $version, $opts, $files, $upgrade, $domuser, $dompass) = @_;
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);

# 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>.");
	}

# Find the radiant binary
local $radiant = &find_rails_command("radiant");
if (!$radiant) {
	return (0, "The <tt>radiant</tt> command could not be found");
	}

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

# As the domain owner, run the radiant command to setup files.
$out = &run_as_domain_user($d, "cd ".quotemeta($opts->{'dir'})." && ".
			       "yes Y | $radiant --database mysql".
			       ($upgrade ? " --force" : "")." . 2>&1");
if ($?) {
	return (0, "Radiant CMS setup failed : <pre>$out</pre>");
	}

# Choose a password, at least 5 characters long
local $longpass = $dompass;
if (length($longpass) < 5) {
	$longpass .= "12345";
	}

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

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

	# Create the database
	local $answers = &transname();
	&open_tempfile(ANSWERS, ">$answers", 0, 1);
	&print_tempfile(ANSWERS, "y\n");		# Destroy data
	&print_tempfile(ANSWERS, "$d->{'owner'}\n");	# Admin user name
	&print_tempfile(ANSWERS, "$domuser\n");		# Admin login
	&print_tempfile(ANSWERS, "$longpass\n");	# Admin password
	&print_tempfile(ANSWERS, "3\n");		# Styled blog
	&close_tempfile(ANSWERS);
	&set_ownership_permissions($d->{'uid'}, $d->{'ugid'}, undef, $answers);
	$out = &run_as_domain_user($d, "cd ".quotemeta($opts->{'dir'})." && ".
			      "rake production db:bootstrap <$answers 2>&1");
	if ($?) {
		return (-1, "Radiant CMS database setup failed : ".
			   "<pre>$out</pre>");
		}
	}

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

# Start the servers
local (@logs, @startcmds, @stopcmds);
local @ports = split(/\s+/, $opts->{'port'});
local $err = &mongrel_rails_start_servers($d, $opts, "radiant", \@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, "radiant-".$ports[0],
			       "Radiant CMS Blog Engine");
	}

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, "Radiant CMS installation complete. Go to <a target=_blank href='$adminurl'>$adminurl</a> to manage it.", "Under $rp", $url, $domuser, $longpass);
}

# script_radiant_uninstall(&domain, version, &opts)
# Un-installs a Radiant installation, by deleting the directory and database.
# Returns 1 on success and a message, or 0 on failure and an error
sub script_radiant_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
&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 /radiant
&delete_mongrel_proxy($d, $opts->{'path'});
&register_post_action(\&restart_apache);

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

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

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

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

sub script_radiant_check_latest
{
local ($ver) = @_;
foreach my $nv (&ruby_gem_versions("radiant")) {
	return $nv if (&compare_versions($nv, $ver) > 0);
	}
return undef;
}

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

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

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

sub script_radiant_site
{
return 'http://radiantcms.org/';
}

sub script_radiant_passmode
{
return 1;
}

sub script_radiant_disabled
{
return 1;
}

1;

