
# script_friendica_desc()
sub script_friendica_desc
{
return "Friendica";
}

sub script_friendica_uses
{
return ( "php" );
}

# script_friendica_longdesc()
sub script_friendica_longdesc
{
return "Friendica a decentralized social network communications platform";
}

# script_friendica_versions()
sub script_friendica_versions
{
return ( "2022.06" );
}

sub script_friendica_release
{
return 1;
}

sub script_friendica_version_desc
{
local ($ver) = @_;
return $ver;
}

sub script_friendica_category
{
return "Community";
}

sub script_friendica_php_vers
{
return ( 5 );
}

sub script_friendica_php_modules
{
my @modules = ( "gd", "xml", "zip", "iconv",
                "mbstring", "mysql" );
return @modules;
}

sub script_friendica_php_optional_modules
{
return ( "openssl", "posix", "pdo", "hash", "imagick" );
}

sub script_friendica_dbs
{
local ($d, $ver) = @_;
return ("mysql");
}

sub script_friendica_php_fullver
{
local ($d, $ver, $sinfo) = @_;
return "7.3";
}

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

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

# script_friendica_files(&domain, version, &opts, &upgrade-info)
# Returns a list of files needed by friendica, each of which is a hash ref
# containing a name, filename and URL
sub script_friendica_files
{
local ($d, $ver, $opts, $upgrade) = @_;
my $ver_ = $ver;
$ver_ =~ s/\.//g;
local @files = ( { 'name' => "source",
	   'file' => "friendica_$ver_.zip",
	   'url' => "https://github.com/friendica/friendica/archive/refs/tags/$ver.zip" } );
return @files;
}

sub script_friendica_commands
{
return ("unzip");
}

# script_friendica_install(&domain, version, &opts, &files, &upgrade-info)
# Actually installs friendica, and returns either 1 and an informational
# message, or 0 and an error
sub script_friendica_install
{
local ($d, $version, $opts, $files, $upgrade, $domuser, $dompass) = @_;

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 = $dbtype eq "mysql" ? &mysql_pass($d) : &postgres_pass($d, 1);
local $dbphptype = $dbtype eq "mysql" && $version < 3.6 ? "mysql" :
		   $dbtype eq "mysql" ? "mysqli" : "pgsql";
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'}, "friendica-$ver");
$err && return (0, "Failed to extract source : $err");


# Make cache writable
&make_file_php_writable($d, "$opts->{'dir'}/view/smarty3");

my $p = &domain_has_website($d);
my $d_ssl = domain_has_ssl($d);
my $ws = $p eq 'web' ? 'apache' : ($p eq 'virtualmin-nginx' ? 'nginx' : undef);
my $url = &script_path_url($d, $opts);

&run_as_domain_user($d, "cd $opts->{'dir'} && bin/composer.phar install --no-dev");

if ($upgrade) {
	# Remove un-needed files
	unlink_file("$opts->{'dir'}/.htaccess-dist");
	}
else {
	&create_script_php_cron($d, $opts->{'dir'}."/bin/worker.php",
					$opts->{'phpver'}, '10', '*');

	# Type of web-server
	my $htaccess_file = "$opts->{'dir'}/.htaccess";
	if ($ws eq 'apache') {
		rename_file("$opts->{'dir'}/.htaccess-dist", $htaccess_file);
		}
	
	local $cfile = "$opts->{'dir'}/config/local.config.php";
	&open_tempfile_as_domain_user($d, CONFIG, ">$cfile");
	&print_tempfile(CONFIG,
		"<?php\n".
		"return [\n".
		"	'database' => [\n".
		"		'hostname' => '$dbhost',\n".
		"		'username' => '$dbuser',\n".
		"		'password' => '$dbpass',\n".
		"		'database' => '$dbname',\n".
		"		'charset' => 'utf8mb4',\n".
		"	],\n".
		"	'config' => [\n".
		"		'admin_email' => '$d->{'emailto_addr'}',\n".
		"		'sitename' => 'Friendica Social Network',\n".
		"		'hostname' => '$d->{'dom'}',\n".
		"		'register_policy' => \\Friendica\\Module\\Register::OPEN,\n".
		"		'register_text' => '',\n".
		"	],\n".
		"	'system' => [\n".
		"		'default_timezone' => 'UTC',\n".
		"		'language' => 'en',\n".
		"	],\n".
		"];\n");
	&close_tempfile_as_domain_user($d, CONFIG);
	&make_file_php_writable($d, "$cfile");

	# Call post-install URLs
	$ipage = "$opts->{'path'}/install/";
	foreach my $step (2,3,4,5) {
		my ($iout, $ierror);
		my @params = (
			[ "pass", $step ],
			[ "config-php_path", "/usr/bin/php" ],
			[ "system-basepath", $opts->{'dir'} ],
			[ "system-urlpath", "/$in{'dir'}" ],
			[ "system-ssl_policy", '1' ],
			[ "config-hostname", $d->{'dom'} ],
			[ "database-hostname", $dbhost ],
			[ "database-username", $dbuser ],
			[ "database-password", $dbpass ],
			[ "database-database", $dbname ],
			[ "config-admin_email", $d->{'emailto_addr'} ],
			[ "system-default_timezone", 'UTC' ],
			[ "system-language", "en" ]);
		my $params = join("&", map { $_->[0]."=".&urlize($_->[1]) } @params);
		&post_http_connection($d, $ipage, $params, \$iout, \$ierror);
		if ($ierror) {
			return (-1, "Friendica automatic setup failed : $ierror.<br>Setup must be finished <a target='_blank' href='$url'>manually</a>.");
			}
		}
}
# Return a URL for the user
local $rp = $opts->{'dir'};
$rp =~ s/^$d->{'home'}\///;
my $rpf = $opts->{'path'};
$rpf = "" if ($rpf eq "/");
my $nginx_msg = $ws eq 'nginx' ? "<br>Nginx users must first follow an official <a target='_blank' href='https://github.com/friendica/friendica/wiki/Nginx-Install-Guide'>installation guide</a> to get Friendica up and running with Nginx." : '';
my $msg1 = ($upgrade ? "Friendica upgrade complete" : "Friendica initial installation complete");
my $msg2 = ($upgrade ? "manage it." : "complete setup process by registering a new admin user with virtual server's default <tt>$d->{'emailto_addr'}</tt> email address.$nginx_msg");
my $reg = ($upgrade ? "" : "register");
return (1, "$msg1. Go to <a target=_blank href='$url$reg'>$d->{'dom'}$rpf".($reg ? "/$reg" : "")."</a> to $msg2<br>", "Under $rp", $url);

}

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

# Remove Friendica tables from the database
&cleanup_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);

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

&delete_script_php_cron($d, $opts->{'dir'}."/bin/worker.php");

return (1, "Deleted Friendica directory, tables and cron job.");
}

# script_friendica_latest(version)
# Returns a URL and regular expression or callback func to get the version
sub script_friendica_latest
{
return ( "https://github.com/friendica/friendica/tags", 
         'friendica/friendica/releases/tag/([\\d\\.]+)' );
}

sub script_friendica_site
{
return 'https://friendi.ca';
}

sub script_friendica_passmode
{
return 0;
}

1;
