
@helpcenter_tables = ( "activity", "assigns", "canned", "chat", "cobrowse", "coforms", "comarker", "departments", "files", "footprints", "hotpages", "notes", "operators", "polling", "sessions", "stats_referrers", "stats_visitors", "system", "traffic", "transcripts", "reviews");

# script_helpcenter_desc()
sub script_helpcenter_desc
{
return "Help Center Live";
}

sub script_helpcenter_uses
{
return ( "php" );
}

sub script_helpcenter_longdesc
{
return "A problem reporting and help desk application";
}

# script_helpcenter_versions()
sub script_helpcenter_versions
{
return ( "2.1.7" );
}

sub script_helpcenter_disabled
{
return 1;
}

sub script_helpcenter_category
{
return "Helpdesk";
}

sub script_helpcenter_php_vers
{
return ( 5 );
}

sub script_helpcenter_php_modules
{
return ("mysql");
}

sub script_helpcenter_perl_modules
{
return ( "Digest::MD5" );
}

sub script_helpcenter_dbs
{
return ("mysql");
}

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

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

# script_helpcenter_files(&domain, version, &opts, &upgrade-info)
# Returns a list of files needed by Wordpress, each of which is a hash ref
# containing a name, filename and URL
sub script_helpcenter_files
{
local ($d, $ver, $opts, $upgrade) = @_;
local @files = ( { 'name' => "source",
	   'file' => "hcl_$ver.zip",
	   'url' => "http://osdn.dl.sourceforge.net/sourceforge/helpcenterlive/hcl-$ver.zip" } );
return @files;
}

sub script_helpcenter_commands
{
return ("unzip");
}

# script_helpcenter_install(&domain, version, &opts, &files, &upgrade-info)
# Actually installs Help Center Live, and returns either 1 and an informational
# message, or 0 and an error
sub script_helpcenter_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 = $dbtype eq "mysql" ? &mysql_user($d) : &postgres_user($d);
local $dbpass = $dbtype eq "mysql" ? &mysql_pass($d) : &postgres_pass($d, 1);
local $dbhost = &get_database_host($dbtype, $d);
local $dbphptype = $dbtype eq "mysql" ? "mysql" : "psql";
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'}, "hcl");
$err && return (0, "Failed to extract source : $err");
local $cfile = "$opts->{'dir'}/config.php";

# Update the config file
local $url = &script_path_url($d, $opts);
local $lref = &read_file_lines_as_domain_user($d, $cfile);
local $l;
foreach $l (@$lref) {
	if ($l =~ /^\s*\$conf\['database'\]\s*=/) {
		$l = "\$conf['database'] = '$dbname';";
		}
	if ($l =~ /^\s*\$conf\['username'\]\s*=/) {
		$l = "\$conf['username'] = '$dbuser';";
		}
	if ($l =~ /^\s*\$conf\['password'\]\s*=/) {
		$l = "\$conf['password'] = '".&php_quotemeta($dbpass, 1)."';";
		}
	if ($l =~ /^\s*\$conf\['host'\]\s*=/) {
		$l = "\$conf['host'] = '$dbhost';";
		}
	if ($l =~ /^\s*\$conf\['url'\]\s*=/) {
		local $noslash = $url;
		$noslash =~ s/\/$//;
		$l = "\$conf['url'] = '$noslash';";
		}
	if ($l =~ /^\s*\$conf\['prefix'\]\s*=/) {
		$l = "\$conf['prefix'] = '';";
		}
	}
&flush_file_lines_as_domain_user($d, $cfile);
&run_as_domain_user($d, "find ".quotemeta($opts->{'dir'})." -name config.php | xargs chmod 777");

# Turn off osTicket
local $osticket = "$opts->{'dir'}/modules/osTicket/hcl/config.php";
if (-r $osticket) {
	local $lref = &read_file_lines_as_domain_user($d, $osticket);
	foreach $l (@$lref) {
		if ($l =~ /^\s*\$GLOBALS\['conf'\]\['modules'\]\['osTicket'\]\['active'\]\s*=\s*true/) {
			$l =~ s/true/false/g;
			}
		}
	&flush_file_lines_as_domain_user($d, $osticket);
	}

# Run database SQL script
local $sqlfile = "$opts->{'dir'}/setup/database.sql";
&require_mysql();
local ($ex, $out) = &mysql::execute_sql_file($dbname, $sqlfile, $dbuser, $dbpass);
$ex && return (0, "Failed to run database setup script : <tt>$out</tt>.");

# Create admin user
eval "use Digest::MD5";
local $md5;
if (!$@) {
	$md5 = Digest::MD5::md5_hex($dompass);
	}
&mysql::execute_sql_logged($dbname, "insert into operators values (NULL, '$domuser', '$md5', 'Default', 'User', '$d->{'emailto_addr'}', 0, 0, 1, 0, 0, 1, '', 0, 0, 0, 0, 0, 0, 0, 0)");

# Remove the setup directory
&unlink_file_as_domain_user($d, "$opts->{'dir'}/setup");

# Return a URL for the user
local $rp = $opts->{'dir'};
$rp =~ s/^$d->{'home'}\///;
local $adminurl = $url."admin/";
return (1, "Help Center Live installation complete. It can be accessed at <a target=_blank href='$adminurl'>$adminurl</a>.", "Under $rp using $dbphptype database $dbname", $url, $domuser, $dompass);
}

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

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

# Remove all known help center tables from the database
&cleanup_script_database($d, $opts->{'db'}, \@helpcenter_tables);

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

return (1, "Help Center Live directory and tables deleted.");
}

# script_helpcenter_check_latest(version)
# Checks if some version is the latest for this project, and if not returns
# a newer one. Otherwise returns undef.
sub script_helpcenter_check_latest
{
local ($ver) = @_;
local @vers = &osdn_package_versions("helpcenterlive", "hcl-(2\\.[0-9\\.]+)\\.zip");
return "Failed to find versions" if (!@vers);
return $ver eq $vers[0] ? undef : $vers[0];
}

sub script_helpcenter_site
{
return 'http://www.helpcenterlive.com/';
}

sub script_helpcenter_passmode
{
return 1;
}

1;

