#!/usr/local/bin/perl

=head1 set-php-directory.pl

Set the version of PHP to run in some directory

If more than one version of PHP is installed on your system and either CGI
or fCGId is used to run PHP scripts in some virtual server, it can be configured
to run a different PHP version on a per-directory basis. This is most useful
when running PHP applications that only support specific versions.

To set a PHP directory, the C<--domain> flag must be used to specify the
directory, C<--dir> to set the path (like C<horde> or C</home/domain/public_html/horde>),
and C<--version> to set the version number.

=cut

package virtual_server;
if (!$module_name) {
	$main::no_acl_check++;
	$ENV{'WEBMIN_CONFIG'} ||= "/etc/webmin";
	$ENV{'WEBMIN_VAR'} ||= "/var/webmin";
	if ($0 =~ /^(.*)\/[^\/]+$/) {
		chdir($pwd = $1);
		}
	else {
		chop($pwd = `pwd`);
		}
	$0 = "$pwd/set-php-directory.pl";
	require './virtual-server-lib.pl';
	$< == 0 || die "set-php-directory.pl must be run as root";
	}
@OLDARGV = @ARGV;

# Parse command-line args
$owner = 1;
while(@ARGV > 0) {
	my $a = shift(@ARGV);
	if ($a eq "--domain") {
		$domain = shift(@ARGV);
		}
	elsif ($a eq "--dir") {
		$dir = shift(@ARGV);
		}
	elsif ($a eq "--version") {
		$version = shift(@ARGV);
		}
	elsif ($a eq "--multiline") {
		$multiline = 1;
		}
	elsif ($a eq "--help") {
		&usage();
		}
	else {
		&usage("Unknown parameter $a");
		}
	}

# Validate inputs
$domain || &usage("No domain specified");
$dir || &usage("No directory specified");
$version || &usage("No PHP version specified");
$d = &get_domain_by("dom", $domain);
$d || usage("Virtual server $domain does not exist");
$mode = &get_domain_php_mode($d);
$mode eq "mod_php" &&
    usage("The PHP version cannot be set for virtual servers using mod_php");
$mode eq "none" &&
    usage("The PHP version cannot be set for virtual servers with PHP disabled");
@avail = map { $_->[0] } &list_available_php_versions($d);
&indexof($version, @avail) >= 0 ||
    usage("Only the following PHP version are available : ".join(" ", @avail));
if ($dir eq ".") {
	$dir = &public_html_dir($d);
	}
elsif ($dir !~ /^\//) {
	$dir = &public_html_dir($d)."/".$dir;
	}

# Make the change
&obtain_lock_web($d);
&set_all_null_print();
$err = &save_domain_php_directory($d, $dir, $version);
&usage($err) if ($err);
$err = &save_domain_php_mode($d, $mode);
&usage($err) if ($err);
&release_lock_web($d);
&clear_links_cache($d);
&refresh_webmin_user($d);
&run_post_actions();
&virtualmin_api_log(\@OLDARGV, $d);

sub usage
{
print "$_[0]\n\n" if ($_[0]);
print "Sets the version of PHP to be used in some web directory.\n";
print "\n";
print "virtualmin set-php-directory --domain domain.name\n";
print "                             --dir directory|url-path|\".\"\n";
print "                             --version num\n";
exit(1);
}

