#!/bin/bash

# Copyright: 2023 Virtuozzo International GmbH

# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at

# http://www.apache.org/licenses/LICENSE-2.0

# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

[ -n "${APACHEPHPSSLLIB_VERSION:-}" ] && return 0;
APACHEPHPSSLLIB_VERSION="0.1";

$PROGRAM 'sed';
$PROGRAM 'grep';

SERVER_XML_CONFIG="/etc/httpd/conf.d/ssl.conf";

function enableSSL(){
	local default_httpd_conf="/etc/sysconfig/httpd"
	[ ! -e ${default_httpd_conf} ] && touch ${default_httpd_conf};
	$GREP -q "OPENSSL_NO_DEFAULT_ZLIB" $default_httpd_conf || echo "export OPENSSL_NO_DEFAULT_ZLIB=1" >>  $default_httpd_conf;
	local err;
	local msg;
	msg=$(doAction keystore DownloadKeys 2>&1);
	err=$?;
	# [ -z "$msg" ] || echo "$msg" | $SED -re 's|.*result.*message\":||' -e 's|\}||' >>$ACTIONS_LOG;
	[[ ${err} -gt 0 ]] && exit "$err";
	[ -f "$SERVER_XML_CONFIG" ] || return 39
	$SED -i 's/SSLEngine=\"off\"/SSLEnabled=\"on\"/g' $SERVER_XML_CONFIG 2>$ACTIONS_LOG || return 143
	msg=$(doAction apache2ext enmod ssl > /dev/null 2>&1) ||  { writeJSONResponseErr "result=>4020" "message=>Cannot enable SSL module!"; return 220; }
}

function disableSSL(){
	local err;
	local msg=$(doAction keystore remove 2>&1);
	err=$?; [[ ${err} -gt 0 ]] && exit "$err";
	[ -f "$SERVER_XML_CONFIG" ] && { $SED -i 's/SSLEngine=\"on\"/SSLEnabled=\"off\"/g' $SERVER_XML_CONFIG 2>$ACTIONS_LOG || return 143; }
	msg=$(doAction apache2ext dismod ssl > /dev/null 2>&1) ||  { writeJSONResponseErr "result=>4021" "message=>Cannot disable SSL module!"; return 221; };
}
