
# script_rails_desc()
sub script_rails_desc
{
return "Ruby on Rails";
}

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

sub script_rails_longdesc
{
return "An open-source web framework that's optimized for programmer happiness and productivity";
}

# script_rails_versions()
sub script_rails_versions
{
return ( "2.3.8", "7.0.4" );
}

sub script_rails_category
{
return "Development";
}

sub script_rails_abandoned
{
return 1;
}

sub script_rails_gems
{
my ($d, $ver, $opts) = @_;
my @rv = &get_ruby_rails_gems();
if ($ver >= 4) {
	push(@rv, [ "rmagick", undef, 0 ],
		  [ "sass-rails", undef, 0, 1 ],
  		  [ "uglifier", undef, 0, 1 ],
		  [ "coffee-rails", undef, 0, 1 ],
		  [ "jquery-rails", undef, 0, 1 ],
		  [ "turbolinks", undef, 0, 1 ],
		  [ "jbuilder", undef, 0, 1 ],
		  [ "sdoc", undef, 0, 1 ],
		  [ "debugger", undef, 0, 1, 1 ],
		  [ "web-console", undef, 0, 1 ],
		  [ "spring", undef, 0, 1 ],
		  [ "execjs", undef, 0, 1 ],
	    );
	}
return @rv;
}

# script_rails_depends(&domain, version)
# Check for ruby command, ruby gems, mod_proxy
sub script_rails_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");
if ($ver >= 5) {
	local $rver = &get_ruby_version();
	if (&compare_versions($rver, "2.2.2") < 0) {
		push(@rv, "Ruby version 2.2.2 or later is needed, but your ".
			  "system has version $rver");
		}
	}
return @rv;
}

# script_rails_params(&domain, version, &upgrade-info)
# Returns HTML for table rows for options for installing PHP-NUKE
sub script_rails_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);
	local ($dbtype, $dbname) = split(/_/, $upgrade->{'opts'}->{'db'}, 2);
	if ($dbtype) {
		$rv .= &ui_table_row("Rails database", $dbname);
		}
	$rv .= &ui_table_row("Run Rails server?",
		$upgrade->{'opts'}->{'server'} ? "Yes" : "No");
	$rv .= &ui_table_row("Use development mode?",
		$upgrade->{'opts'}->{'development'} ? "Yes" : "No");
	}
else {
	# Show editable install options
	$rv .= &ui_table_row("Install sub-directory under <tt>$hdir</tt>",
			     &ui_opt_textbox("dir", &substitute_scriptname_template("ror", $d), 30, "At top level"));
	local @dbs = &domain_databases($d, [ "mysql" ]);
	if (@dbs) {
		$rv .= &ui_table_row("Configure Rails to use database",
		     &ui_radio("db_def", 1, [ [ 1, "None" ],
				     	    [ 0, "Selected database" ] ])."\n".
		     &ui_database_select("db", undef, \@dbs));
		}
	else {
		$rv .= &ui_hidden("db_def", 1)."\n";
		}
	$rv .= &ui_table_row("Run Mongrel server?",
			     &ui_yesno_radio("server", 1));
	$rv .= &ui_table_row("Use development mode?",
			     &ui_yesno_radio("development", 0));
	$rv .= &show_mongrels_ports_input($d);
	}
return $rv;
}

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

# script_rails_check(&domain, version, &opts, &upgrade-info)
# Returns an error message if a required option is missing or invalid
sub script_rails_check
{
local ($d, $ver, $opts, $upgrade) = @_;
if (-r "$opts->{'dir'}/script/server") {
	return "Ruby on Rails appears to be already installed in the selected directory";
	}
$opts->{'mongrels'} ||= 1;
return undef;
}

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

sub script_rails_commands
{
local ($d, $ver, $opts) = @_;
return ("ruby", $opts->{'db'} ? ("gcc", "make") : ( ));
}

sub script_rails_packages
{
my ($d, $ver) = @_;
my @rv = &get_ruby_rails_packages();
if ($ver >= 4) {
	if ($gconfig{'os_type'} eq 'debian-linux') {
		push(@rv, "nodejs");
		}
	}
return @rv;
}

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

# script_rails_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_rails_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
local ($dbtype, $dbname) = split(/_/, $opts->{'db'}, 2);
local $dbuser = &mysql_user($d);
local $dbpass = &mysql_pass($d);
local $dbhost = &get_database_host($dbtype, $d);
if ($dbtype) {
	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>.");
	}

# As root, run gem to install or update rails
local $err = &install_ruby_gem("rails", $version, 1);
if ($err) {
	return (0, "Rails GEM install failed : <pre>$err</pre>");
	}

# Run gem to install Mongrel - but we can go on if this fails
$err = &install_ruby_gem("mongrel");

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

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

if ($opts->{'server'} && $upgrade) {
	# If the server is running, stop it
	&script_rails_stop_server($d, $opts);
	}

# As the domain owner, run the rails command to setup files
local $rails = &find_rails_command("rails");
$rails || return (0, "Rails command was not found!");
local $op = $ver >= 3 ? "new" : "";
$out = &run_as_domain_user($d, "cd ".quotemeta($opts->{'dir'})." && ".
			       "$rails $op . 2>&1");
if ($?) {
	return (0, "Rails setup failed : <pre>$out</pre>");
	}

if (!$upgrade && $dbname) {
	# Create database configuration file for MySQL
	local $dbfile = "$opts->{'dir'}/config/database.yml";
	&open_tempfile_as_domain_user($d, DBFILE, ">$dbfile");
	foreach my $mode ("development", "production", "test") {
		&print_tempfile(DBFILE, $mode.":\n",
					"  adapter: mysql\n",
					"  database: $dbname\n",
					"  username: $dbuser\n",
					"  password: $dbpass\n",
					"  host: $dbhost\n",
					"\n");
		}
	&close_tempfile_as_domain_user($d, DBFILE);
	}

if (!$upgrade) {
	# Create secret keys
	local $sfile = "$opts->{'dir'}/config/secrets.yml";
	&open_tempfile_as_domain_user($d, SFILE, ">$sfile");
	foreach my $mode ("development", "production", "test") {
                &print_tempfile(SFILE,
			$mode.":\n",
			"  secret_key_base: ",&random_password(32),"\n",
			"  secret_token: ",&random_password(32),"\n",
			"\n");
		}
	&close_tempfile_as_domain_user($d, SFILE);
	}

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

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

local (@logs, @startcmds, @stopcmds);
local @ports = split(/\s+/, $opts->{'port'});
$opts->{'rails_server'} = $version >= 4 ? 1 : 0;
if ($opts->{'server'}) {
	# Start the servers
	local $err = &mongrel_rails_start_servers($d, $opts, "rails",
					\@startcmds, \@stopcmds, \@logs);
	return (-1, $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 ($opts->{'server'} && !$upgrade) {
	# Configure server to start at boot
	&setup_mongrel_startup($d,
			       join("\n", @startcmds),
			       join("\n", @stopcmds),
			       $opts,
			       1, "rails-".$ports[0], "Ruby on Rails");
	}

if ($opts->{'server'} && !$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 Ruby on Rails installation complete. Go to <a target=_blank href='$url'>$url</a> to use it. Rails is a development environment, so it doesn't do anything by itself!", "Under $rp", $url);
}

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

if ($opts->{'server'}) {
	# Shut down the server process
	&script_rails_stop_server($d, $opts);

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

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

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

return (1, "Ruby on Rails directory deleted.");
}

# script_rails_stop(&domain, &sinfo)
# Stop running mongrel process
sub script_rails_stop
{
local ($d, $sinfo) = @_;
if ($sinfo->{'opts'}->{'server'}) {
	&script_rails_stop_server($d, $sinfo->{'opts'});
	&delete_mongrel_startup($d, $sinfo->{'opts'},
			"mongrel_rails start", $sinfo->{'opts'}->{'port'});
	&delete_mongrel_startup($d, $sinfo->{'opts'},
			"script/server", $sinfo->{'opts'}->{'port'});
	}
}

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

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

# script_rails_stop_server(&domain, &opts)
# Kill the running Rails server process
sub script_rails_stop_server
{
local ($d, $opts) = @_;
&mongrel_rails_stop_servers($d, $opts);
}

sub script_rails_check_latest
{
local ($ver) = @_;
foreach my $nv (&ruby_gem_versions("rails")) {
	next if ($ver < 3 && $nv >= 3);
	return $nv if (&compare_versions($nv, $ver) > 0);
	}
return undef;
}

sub script_rails_site
{
return 'http://www.rubyonrails.org/';
}

sub script_rails_disabled
{
return 1;
}

1;

