
# script_yourls_desc()
sub script_yourls_desc
{
return "YOURLS";
}

sub script_yourls_uses
{
return ( "php" );
}

sub script_yourls_longdesc
{
return "YOURLS allows you to run your own URL shortening service";
}

# script_yourls_versions()
sub script_yourls_versions
{
return ( "1.9.1" );
}

sub script_yourls_php_vers
{
return ( 5 );
}

sub script_yourls_php_modules
{
return ("mysql");
}

sub script_yourls_dbs
{
return ("mysql");
}

sub script_yourls_php_fullver
{ 
local ($d, $ver, $sinfo) = @_;
return &compare_versions($ver, 1.8) >= 0 ? 7.2 : 5.6;
}

# script_yourls_params(&domain, version, &upgrade-info)
# Returns HTML for table rows for options for installing YOURLS
sub script_yourls_params
{
my ($d, $ver, $upgrade) = @_;
my $rv;
my $hdir = &public_html_dir($d, 1);
if ($upgrade) {
	# Options are fixed when upgrading
	my $dir = $upgrade->{'opts'}->{'dir'};
	$dir =~ s/^$d->{'home'}\///;
	$rv .= &ui_table_row("Install directory", $dir);
	}
else {
	# Show editable install options
	my @dbs = &domain_databases($d, [ "mysql" ]);
	$rv .= &ui_table_row("Database for YOURLS tables",
&ui_database_select("db", undef, \@dbs, $d, "yourls"));
	$rv .= &ui_table_row("Install sub-directory under <tt>$hdir</tt>",
			     &ui_opt_textbox("dir", &substitute_scriptname_template("yourls", $d), 30, "At top level"));
	}
return $rv;
}

# script_yourls_parse(&domain, version, &in, &upgrade-info)
# Returns either a hash ref of parsed options, or an error string
sub script_yourls_parse
{
my ($d, $ver, $in, $upgrade) = @_;
if ($upgrade) {
	# Options are always the same
	return $upgrade->{'opts'};
	}
else {
	my $hdir = &public_html_dir($d, 0);
	$in{'dir_def'} || $in{'dir'} =~ /\S/ && $in{'dir'} !~ /\.\./ ||
		return "Missing or invalid installation directory";
	my $dir = $in{'dir_def'} ? $hdir : "$hdir/$in{'dir'}";
	my ($newdb) = ($in->{'db'} =~ s/^\*//);
	return { 'db' => $in->{'db'},
		 'newdb' => $newdb,
		 'dir' => $dir,
		 'path' => $in{'dir_def'} ? "/" : "/$in{'dir'}", };
	}
}

# script_yourls_check(&domain, version, &opts, &upgrade-info)
# Returns an error message if a required option is missing or invalid
sub script_yourls_check
{
my ($d, $ver, $opts, $upgrade) = @_;
$opts->{'dir'} =~ /^\// || return "Missing or invalid install directory";
$opts->{'db'} || return 'Missing database';

if (-r "$opts->{'dir'}/yourls-go.php") {
	return "YOURLS appears to be already installed in the selected directory";
	}
my ($dbtype, $dbname) = split(/_/, $opts->{'db'}, 2);
my $clash = &find_database_table($dbtype, $dbname, "yourls_.*");
$clash && return "YOURLS appears to be already using the selected database (table <tt>$clash</tt> exists)";
return undef;
}

# script_yourls_files(&domain, version, &opts, &upgrade-info)
# Returns a list of files needed by YOURLS, each of which is a hash ref
# containing a name, filename and URL
sub script_yourls_files
{
my ($d, $ver, $opts, $upgrade) = @_;
my @files = ( { 'name' => "source",
	   'file' => "yourls-$ver.tar.gz",
	   'nocache' => 1,
	   'url' => "https://github.com/YOURLS/YOURLS/archive/$ver.tar.gz" } );
return @files;
}

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

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

# Create or check db
if ($opts->{'newdb'} && !$upgrade) {
        my $err = &create_script_database($d, $opts->{'db'});
        return (0, "Database creation failed : $err") if ($err);
        }
my ($dbtype, $dbname) = split(/_/, $opts->{'db'}, 2);
my $dbuser = &mysql_user($d);
my $dbpass = &mysql_pass($d);
my $dbhost = &get_database_host("mysql", $d);
my $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
my $temp = &transname();
my $err = &extract_script_archive($files->{'source'}, $temp, $d,
                                  $opts->{'dir'}, "YOURLS-$version");
$err && return (0, "Failed to extract source : $err");
my $cfile = "$opts->{'dir'}/user/config.php";

# Copy and modify config-sample.php
unless ($upgrade) {
# Setup some options to change in the sample config
my $url = script_path_url($d, $opts);
# remove the trailing slash
$url = $1 if($url=~/(.*)\/$/);
my %cfile_opts = (
	'YOURLS_DB_USER' => $dbuser,
	'YOURLS_DB_PASS' => $dbpass,
	'YOURLS_DB_NAME' => $dbname,
	'YOURLS_DB_HOST' => $dbhost,
	'YOURLS_DB_PREFIX' => 'yourls_',
	'YOURLS_SITE' => "$url",
	'YOURLS_COOKIE' => cookie_key(),
);

&copy_source_dest("$opts->{'dir'}/user/config-sample.php", $cfile);

# Configure it
my $lref = read_file_lines_as_domain_user($d, $cfile);
foreach my $l (@$lref) {
	foreach my $opt (keys %cfile_opts) {
		if ($l =~ $opt) {
			$l = "define( '$opt', '$cfile_opts{$opt}' );"
		}
	}
	# setup a user and password
	if ($l =~ "'username' => 'password',") {
		$l = "\t'$domuser' => '$dompass',"
	}
}

flush_file_lines_as_domain_user($d, $cfile);

# Call installation page
my ($iout, $ierror);
my @params = ( [ "install", 1 ] );
my $params = join("&", map { $_->[0]."=".&urlize($_->[1]) } @params);
my $ipage = "$opts->{'path'}/admin/install.php";
&post_http_connection($d, $ipage, $params, \$iout, \$ierror);

}

my $url = &script_path_url($d, $opts) . 'admin';
my $rp = $opts->{'dir'};
$rp =~ s/^$d->{'home'}\///;
return (1, "YOURLS installation complete. Go to <a target=_blank href='$url'>$url</a> to use it.", "Under $rp", $url, $domuser, $dompass);
}

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

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

cleanup_script_database($d, $opts->{'db'}, 'yourls_');

# remove the DB, if one was created
if ($opts->{'newdb'}) {
	delete_script_database($d, $opts->{'db'});
}

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

# script_yourls_latest()
# Returns a URL and regular expression or callback func to get the version
sub script_yourls_latest
{
return ( "https://github.com/YOURLS/YOURLS/tags",
         "([0-9\\.]+)\\.tar.gz" );
}

sub script_yourls_site
{
return 'https://yourls.org/';
}

sub script_yourls_passmode
{
return (1, 4);
}

sub cookie_key
{
seed_random();
my $cookie_key;
my @chars=('a'..'z','A'..'Z','0'..'9','_');
foreach (1 .. 64) {
        $cookie_key .= $chars[rand(scalar(@chars))];
        }
return $cookie_key;
}

1;

