package SB::CPServer;

use strict;
use warnings;
use SB::Defaults qw($CONFIG);
use SB::Logging qw($Logger INFO DEBUG FATAL ERROR WARNING);
use SB::Utils qw(restorecon run);
require SB::OS;

BEGIN {
		use Exporter;
		our (@ISA, $VERSION, @EXPORT, @EXPORT_OK);
		$VERSION   = 4.00;
		@ISA 	   = qw(Exporter);
		@EXPORT    = qw();
		@EXPORT_OK = qw();
}

sub makeLighttpdConfig {
	unless (-e "/etc/init.d/sw-cp-server") {
		$Logger->Log(ERROR, "sw-cp-server not found");
		return 1;
	}

	$Logger->Log(INFO, "Sitebuilder will be at port " . ($CONFIG->{'internal'}->{'httpd_port'} = 6443));
	$Logger->Log(WARNING, "SSL is not (yet) supported on sw-cp-server") if $CONFIG->{'internal'}->{'enable_ssl'};

	my $prefix = SB::OS::getInstallPrefix();
	my $filePath 	= $prefix . "/utils/lighttpd.conf.in";

	my $sb_hostname = $CONFIG->{"internal"}->{"sb_hostname"};
	my $httpd_port	= $CONFIG->{"internal"}->{"httpd_port"};
	my ($owner,$group)	= split(':', $CONFIG->{'internal'}->{'httpd_owner'});
	my $host_ip 	= $CONFIG->{"internal"}->{'sb_host_ip'};
	my $phpcgi_path = $CONFIG->{"internal"}->{"phpcgi_path"};
	my $errorLogDir = $prefix . "/tmp/sitebuilder3-access.log";

	my $fileContent;
	$owner =~ s/:/ /g;

	{
		unless (open(F, "< $filePath")) {
			$Logger->Log(ERROR, "Cannot open file $filePath: $!");
			return 1;
		}
		binmode(F);
		local $/;
		$fileContent = <F>;
		close(F);
	}

	$fileContent =~ s|%%HOSTIP%%|$host_ip|g;
	$fileContent =~ s|%%SB_PREFIX%%|$prefix|g;
	$fileContent =~ s|%%VHOST_NAME%%|$sb_hostname|g;
	$fileContent =~ s|%%PORT%%|$httpd_port|g;
	$fileContent =~ s|%%PHPPATH%%|$phpcgi_path|g;
	$fileContent =~ s|%%ERRORLOGDIR%%|$errorLogDir|g;
	$fileContent =~ s|%%SB_LIGHTTPD_USER%%|$owner|g;
	$fileContent =~ s|%%SB_LIGHTTPD_GROUP%%|$group|g;

	#get VHOST conf dir
	my $HTTPD_INCLUDE_DIR = "/etc/sw-cp-server/applications.d";

	#get APACHE start command
	my $APACHE_CTL_CMD = "/etc/init.d/sw-cp-server restart";
	my $configpath = $HTTPD_INCLUDE_DIR . "/zz011_sitebuilder.conf";

	unless (open (F,"> $configpath")) {
		$Logger->Log(ERROR, "Cannot create virtual host file $configpath: $!");
		return 1;
	};
	print F $fileContent;
	close(F);
	restorecon($configpath);

	my (undef, $code) = run($APACHE_CTL_CMD);
	if ($code) { 
		$Logger->Log(WARNING, "Cannot reload sw-cp-server. Is it running?");
		return 1;
	}
	$Logger->Log(INFO, "Sitebuilder available at $sb_hostname:$httpd_port"); 
	return 0;
}

1;

