
# script_mt_desc()
sub script_mt_desc
{
return "Movable Type";
}

sub script_mt_uses
{
return ( "perl", "cgi", "apache" );
}

sub script_mt_longdesc
{
return "The Movable Type platform makes it easy for you to both author content and interact with your community of readers";
}

# script_mt_versions()
sub script_mt_versions
{
return ( "7.9.7", "5.2.13" );
}

sub script_mt_category
{
return "Blog";
}

sub script_mt_perl_modules
{
return ( "DBI", "DBD::mysql", "Image::Size",
         "CGI::Cookie", "HTML::Entities" );
}

sub script_mt_dbs
{
return ("mysql");
}

# script_mt_depends(&domain, version)
sub script_mt_depends
{
local ($d, $ver) = @_;
local @rv;
push(@rv, "Movable Type requires Perl version 5.6.1 or later")
	if ($] < 5.006001);
if ($d->{'virtualmin-google-analytics'}) {
	# Analyics below 1.4 corrupts Javascript
	local %minfo = &get_module_info('virtualmin-google-analytics');
	if ($minfo{'version'} < 1.4) {
		push(@rv, "The Virtualmin Analytics feature cannot be ".
			  "enabled when installing Movable Type, unless it ".
			  "is at least version 1.4");
			
		}
	}
return @rv;
}

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

# script_mt_parse(&domain, version, &in, &upgrade-info)
# Returns either a hash ref of parsed options, or an error string
sub script_mt_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_mt_check(&domain, version, &opts, &upgrade-info)
# Returns an error message if a required option is missing or invalid
sub script_mt_check
{
local ($d, $ver, $opts, $upgrade) = @_;
$opts->{'dir'} =~ /^\// || return "Missing or invalid install directory";
if (-r "$opts->{'dir'}/mt.cgi") {
	return "Movable Type appears to be already installed in the selected directory";
	}
local ($dbtype, $dbname) = split(/_/, $opts->{'db'}, 2);
local $clash = &find_database_table($dbtype, $dbname, "mt_");
$clash && return "Movable Type appears to be already using the selected database (table $clash)";
return undef;
}

# script_mt_files(&domain, version, &opts, &upgrade-info)
# Returns a list of files needed by Twiki, each of which is a hash ref
# containing a name, filename and URL
sub script_mt_files
{
local ($d, $ver, $opts, $upgrade) = @_;
local @files = ( { 'name' => "source",
	   'file' => "mt$ver.zip",
	   'nocheck' => 1,
	   'url' => "https://github.com/movabletype/movabletype/archive/refs/tags/mt$ver.zip" } );
return @files;
}

sub script_mt_commands
{
return ("tar", "gunzip");
}

# script_mt_install(&domain, version, &opts, &files, &upgrade-info)
# Actually installs Movable Type, and returns either 1 and an informational
# message, or 0 and an error
sub script_mt_install
{
local ($d, $version, $opts, $files, $upgrade) = @_;
local ($out, $ex);

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

# Extract tar file to temp dir and copy to target
local $temp = &transname();
local $err = &extract_script_archive($files->{'source'}, $temp, $d,
                                     $opts->{'dir'}, "movabletype-mt$version");
$err && return (0, "Failed to extract source : $err");

# Set perl path, based on Webmin
local $pp = &get_perl_path();
$out = &run_as_domain_user($d, "find ".quotemeta($opts->{'dir'})." -name \\*.cgi | $pp $root_directory/perlpath.pl $pp -");
if ($?) {
	return (0, "Failed to set Perl path : <tt>$out</tt>.");
	}

local $url = &script_path_url($d, $opts);
if (!$upgrade) {
	# Create the config file
	local $cfile = "$opts->{'dir'}/mt-config.cgi";
	local $cfileorig = "$opts->{'dir'}/mt-config.cgi-original";
	&run_as_domain_user($d, "cp ".quotemeta($cfileorig)." ".
				       quotemeta($cfile));
	&open_tempfile_as_domain_user($d, CONF, ">$cfile");
	&print_tempfile(CONF, "CGIPath $url\n");
	&print_tempfile(CONF, "StaticWebPath ",$url,"mt-static/\n");
	&print_tempfile(CONF, "DefaultSiteRoot $opts->{'dir'}\n");
	&print_tempfile(CONF, "DefaultSiteURL $url\n");
	&print_tempfile(CONF, "ObjectDriver DBI::mysql\n");
	&print_tempfile(CONF, "Database $dbname\n");
	&print_tempfile(CONF, "DBUser $dbuser\n");
	&print_tempfile(CONF, "DBPassword $dbpass\n");
	&print_tempfile(CONF, "DBHost $dbhost\n");
	&close_tempfile_as_domain_user($d, CONF);
	}

# Enable CGIs for the directory
&require_apache();
local @ports;
push(@ports, $d->{'web_port'}) if ($d->{'web'});
push(@ports, $d->{'web_sslport'}) if ($d->{'ssl'});
foreach my $port (@ports) {
	local ($virt, $vconf, $conf) = &get_apache_virtual($d->{'dom'}, $port);
	next if (!$virt);
	local @dirs = grep { $_ eq $opts->{'dir'} } 
			   &apache::find_directive_struct("Directory", $vconf);
	if ($opts->{'path'} eq '/' && @dirs) {
		# Need to modify root directory block
		local @handlers = &apache::find_directive("AddHandler",
					$dirs[0]->{'members'});
		if (&indexof("cgi-script .cgi", @handlers) < 0) {
			push(@handlers, "cgi-script .cgi");
			&apache::save_directive("AddHandler", \@handlers,
						$dirs[0]->{'members'}, $conf);
			&flush_file_lines($virt->{'file'});
			}
		}
	elsif (!@dirs) {
		local $lref = &read_file_lines($virt->{'file'});
		splice(@$lref, $virt->{'eline'}, 0,
		       "<Directory $opts->{'dir'}>",
		       "Options ExecCGI",
		       "DirectoryIndex mt.cgi index.html",
		       "AddHandler cgi-script .cgi",
		       "</Directory>");
		&flush_file_lines($virt->{'file'});
		undef(@apache::get_config_cache);
		}
	}
&register_post_action(\&restart_apache);

local $rp = $opts->{'dir'};
$rp =~ s/^$d->{'home'}\///;
if ($upgrade) {
	return (1, "Movable Type upgrade complete. Go to <a target=_blank href='$url'>$url</a> to use it.", "Under $rp using $dbtype database $dbname", $url);
	}
else {
	return (1, "Initial Movable Type installation complete. Go to <a target=_blank href='$url'>$url</a> to create your first account and blog.", "Under $rp using $dbtype database $dbname", $url);
	}
}

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

# Remove mt tables from the database
&cleanup_script_database($d, $opts->{'db'}, "mt_");

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

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

# Remove <Directory> section
if ($opts->{'path'} ne '/') {
	&require_apache();
	local @ports;
	push(@ports, $d->{'web_port'}) if ($d->{'web'});
	push(@ports, $d->{'web_sslport'}) if ($d->{'ssl'});
	foreach my $port (@ports) {
		local ($virt, $vconf, $conf) = &get_apache_virtual($d->{'dom'},
								   $port);
		next if (!$virt);
		local ($dir) = grep { $_->{'words'}->[0] eq $opts->{'dir'} } 
			    &apache::find_directive_struct("Directory", $vconf);
		if ($dir) {
			&apache::save_directive_struct(
				$dir, undef, $vconf, $conf);
			&flush_file_lines($dir->{'file'});
			}
		}
	&register_post_action(\&restart_apache);
	}

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

# script_mt_latest()
# Returns a URL and regular expression or callback func to get the version
sub script_mt_latest
{
local ($ver) = @_;
if ($ver >= 7) {
	return ( "https://github.com/movabletype/movabletype/tags",
		 "mt([0-9\\.]+)\\.zip" );
	}
else {
	return ( "https://github.com/movabletype/movabletype/tags?after=mt6.0.8",
	 	 "mt(5\\.[0-9]+\\.[0-9]+)\\.zip" );
	}
}

sub script_mt_site
{
return 'http://www.movabletype.com/';
}

1;

