#!/bin/bash
### Copyright 1999-2021. Plesk International GmbH. All rights reserved.
#

#
# Plesk script
#



#default values


# echo message to product log, also to console in debug mode
p_echo()
{
    if [ -n "$product_log" ] ; then
        echo "$@" >> "$product_log" 2>&1
    fi
    if [ -n "$PLESK_INSTALLER_DEBUG" -o -n "$PLESK_INSTALLER_VERBOSE" -o -z "$product_log" ] ; then
        echo "$@" >&2
    fi
}

# same as p_echo, but without new line
pnnl_echo()
{
	p_echo -n "$@"
}

int_err()
{
	report_problem "internal" "Internal error: $@"
	exit 1
}

p_see_product_log()
{
	log_is_in_dev "${product_log}" || printf " (see log file: ${product_log})" >&2
}

die()
{
	report_problem "fatal" "ERROR while trying to $@"
	printf "Check the error reason" >&2
	p_see_product_log
	echo ", fix and try again" >&2

	selinux_close

	exit 1
}

echo_try()
{
	msg="$*"
	pnnl_echo " Trying to $msg... "
}

suc()
{
	p_echo "done"
}

detect_vz()
{
	[ -z "$PLESK_VZ_RESULT" ] || return $PLESK_VZ_RESULT

	PLESK_VZ_RESULT=1
	PLESK_VZ=0
	PLESK_VE_HW_NODE=0
	PLESK_VZ_TYPE=

	local issue_file="/etc/issue"
	local vzcheck_file="/proc/self/status"
	[ -f "$vzcheck_file" ] || return 1

	local env_id=`sed -ne 's|^envID\:[[:space:]]*\([[:digit:]]\+\)$|\1|p' "$vzcheck_file"`
	[ -n "$env_id" ] || return 1
	if [ "$env_id" = "0" ]; then
		# Either VZ/OpenVZ HW node or unjailed CloudLinux
		PLESK_VE_HW_NODE=1
		return 1
	fi

	if grep -q "CloudLinux" "$issue_file" >/dev/null 2>&1 ; then
		return 1
	fi

	if [ -f "/proc/vz/veredir" ]; then
		PLESK_VZ_TYPE="vz"
	elif [ -d "/proc/vz" ]; then
		PLESK_VZ_TYPE="openvz"
	fi

	PLESK_VZ=1
	PLESK_VZ_RESULT=0
	return 0
}

# detects lxc and docker containers
detect_lxc()
{
	[ -z "$PLESK_LXC_RESULT" ] || return $PLESK_LXC_RESULT
	PLESK_LXC_RESULT=1
	PLESK_LXC=0
	if  { [ -f /proc/1/cgroup ] && grep -q 'docker\|lxc' /proc/1/cgroup; } || \
		{ [ -f /proc/1/environ ] && cat /proc/1/environ | tr \\0 \\n | grep -q "container=lxc"; };
	then
		PLESK_LXC_RESULT=0
		PLESK_LXC=1
	fi
	return "$PLESK_LXC_RESULT"
}

get_ini_conf_var()
{
	local conf="$1"
	local section="$2"
	local param="$3"

	[ -n "$conf" -a -n "$param" ] || die "get_ini_conf_var(): required parameters missing"

	local section_empty=0
	[ -n "$section" ] || section_empty=1

	perl -n -e 'BEGIN { $insect='$section_empty' }
				next if (/^\s*;/);
				$insect=0 if (/^\s*\[.*\]/);
				$insect=1 if (/^\s*\['$section'\]/);
				$val = $2, $val =~ s/\s+$//, print $val . "\n" 
					if ($insect && /^\s*('$param')\s*=\s*([^;\n]*)(;.*)?$/);' $conf | head -n 1
}

problems_log_tail()
{
	[ -f "$product_problems_log" ] || return 0
	{
		tac "$product_problems_log" | awk '/^START/ { exit } { print }' | tac
	} 2>/dev/null
}

product_log_tail()
{
	[ -f "$product_log" ] || return 0
	{
		tac "$product_log" | awk '/^START/ { exit } { print }' | tac
	} 2>/dev/null
}

product_and_problems_log_tail()
{
	product_log_tail
	[ "$product_log" = "$product_problems_log" ] || problems_log_tail
}

log_is_in_dev()
{
	test "${1:0:5}" = "/dev/"
}
### Copyright 1999-2021. Plesk International GmbH. All rights reserved.

construct_report_template()
{
	local severity="${1:-error}"
	local summary="$2"

	local update_ticket="`get_update_ticket`"

	set_error_report_source
	set_error_report_component
	set_error_report_params
	set_error_report_environment

	true construct_report_code construct_report_debug construct_report_message

cat <<-EOL
<?xml version="1.0" encoding="UTF-8" ?>
<error>
  <source>$report_source</source>
  <severity>$severity</severity>
  <datetime>`date --iso-8601=seconds`</datetime>

  <component>$report_component</component>
  <summary><![CDATA[`echo "$summary" | sed -e 's/\]\]>/] ]>/g'`]]></summary>
  <message encoding="base64">`construct_report_message | base64`</message>

  <additional_info>
    <component_params encoding="base64">$report_params</component_params>
    <code encoding="base64">`construct_report_code | base64`</code>
    <debug encoding="base64">`construct_report_debug | base64`</debug>
    <environment encoding="base64">$report_environment</environment>
    <update_ticket>$update_ticket</update_ticket>
  </additional_info>
</error>
EOL
}

construct_report_code()
{
	local call_level=${1:-5}
	local func_level=$[call_level - 1]
	local lineno_func=${BASH_LINENO[ $func_level ]}
	local script_name=${BASH_SOURCE[ $[func_level + 1] ]}

	echo "# Call of ${FUNCNAME[$func_level]}() from ${FUNCNAME[$[func_level + 1]]}() at `readlink -m $script_name`:${BASH_LINENO[$func_level]}"
	head -n $[lineno_func + 4] "$script_name" 2>/dev/null | tail -n 8
}

construct_report_debug()
{
	local call_level=${1:-5}
	call_level=$[call_level-1]

	# Generate calls stack trace.
	for i in `seq $call_level ${#FUNCNAME[@]}`; do
		[ "${FUNCNAME[$i]}" != "main" ] || break

		local func_call="`sed -n -e "${BASH_LINENO[$i]}p" "${BASH_SOURCE[$[i+1]]}" 2>/dev/null |
			sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//'`"
		[ -n "$func_call" -a -z "${func_call##*${FUNCNAME[$i]}*}" ] || func_call="${FUNCNAME[$i]}"
		echo "#$[i - $call_level] `readlink -m ${BASH_SOURCE[$[i+1]]}`(${BASH_LINENO[$i]}): $func_call"
	done
}

construct_report_message()
{
	product_and_problems_log_tail

	echo ""
	if [ -n "$report_context" ]; then
		echo "Context: $report_context"
		echo ""
	fi
	if [ -n "$RP_LOADED_PATCHES" ]; then
		echo "Loaded runtime patches: $RP_LOADED_PATCHES"
		echo ""
	fi
}

# Construct report to send it to our errors tracker
construct_report()
{
	local severity="${1:-error}"
	local summary="$2"

	[ -n "$summary" ] || int_err "Unable to send error report. Some parameters are not defined."

	set_error_report_source
	get_product_versions

	construct_report_template "$severity" "$summary" \
		| $PRODUCT_ROOT_D/admin/bin/send-error-report --version "$product_this_version" $report_source >/dev/null 2>&1
}

# Use this function to report failed actions.
# Typical report should contain
# - reason or problem description (example: file copying failed)
# - how to resolve or investigate problem (example: check file permissions, free disk space)
# - how to re-run action (example: perform specific command, restart bootstrapper script, run installation again)
report_problem()
{
	local severity="${1:-error}"

	# Get first string of error as a summary of report
	shift

	local summary="$1"

	[ -n "$product_problems_log" ] || product_problems_log="/dev/stderr"

	p_echo
	if [ "0$problems_occured" -eq 0 ]; then
		echo "***** $process problem report *****" >> "$product_problems_log" 2>&1
	fi
	for problem_message in "$@"; do
		p_echo "$problem_message"
		if [ "$product_log" != "$product_problems_log" ]; then
			echo "$problem_message" >> "$product_problems_log" 2>&1
		fi
	done
	p_echo

	construct_report "$severity" "$summary"

	[ -n "$PLESK_INSTALLER_DEBUG" -o -n "$PLESK_INSTALLER_VERBOSE" ] || \
		product_log_tail

	problems_occured=1
}

set_error_report_source()
{
	[ -z "$1" ] || report_source="$1"
	[ -n "$report_source" ] || {
		if [ -n "$PACKAGE_ID" -o -n "$PACKAGE_ACTION" -o -n "$PACKAGE_NAME" -o -n "$PACKAGE_VERSION" ]; then
			report_source="install"
		else
			report_source="backend"
		fi
	}
}

set_error_report_component()
{
	local component="$1"

	if [ "$report_source" = "install" ]; then
		[ -n "$report_component" ] || report_component="$PACKAGE_ID"
		return 0
	fi

	[ -z "$component" ] || report_component="$1"
	[ -n "$report_component" ] || report_component="`basename $0`"
}

set_error_report_params()
{
	if [ "$report_source" = "install" ]; then
		[ -n "$report_params" ] || report_params="`echo "$PACKAGE_ACTION of $PACKAGE_NAME $PACKAGE_VERSION" | base64`"
		return 0
	fi

	[ -z "$*" ] || report_params="`echo "$*" | base64`"
	[ -n "$report_params" ] || report_params="`echo "$PLESK_SCRIPT_COMMAND_LINE" | base64`"
}

default_error_report_environment()
{
	detect_vz
	detect_lxc
	local is_docker="`[ -f "/.dockerenv" ] && echo yes || :`"
	local systemd_detect_virt_ct="`/usr/bin/systemd-detect-virt -c 2>/dev/null | grep -v '^none$' || :`"
	local systemd_detect_virt_vm="`/usr/bin/systemd-detect-virt -v 2>/dev/null | grep -v '^none$' || :`"
	local virt_what="`/usr/sbin/virt-what 2>/dev/null | xargs || :`"

	if [ -n "$is_docker" ]; then
		echo "virtualization: docker $virt_what"
	elif [ "$PLESK_VZ" = "1" ]; then
		echo "virtualization: ${PLESK_VZ_TYPE:-virtuozzo}"
	elif [ "$PLESK_LXC" = "1" ]; then
		echo "virtualization: lxc $virt_what"
	elif [ -n "$systemd_detect_virt_ct" ]; then
		echo "virtualization: $systemd_detect_virt_ct $systemd_detect_virt_vm"
	elif [ -n "$virt_what" ]; then
		echo "virtualization: $virt_what"
	elif [ -n "$systemd_detect_virt_vm" ]; then
		echo "virtualization: $systemd_detect_virt_vm"
	fi
}

set_error_report_environment()
{
	[ -z "$*" ] || report_environment="`echo "$*" | base64`"
	[ -n "$report_environment" ] || report_environment="`default_error_report_environment | base64`"
}

get_update_ticket()
{
	[ -r $PRODUCT_ROOT_D/var/update_ticket ] && cat $PRODUCT_ROOT_D/var/update_ticket | awk '{$1=$1};1'
}
### Copyright 1999-2021. Plesk International GmbH. All rights reserved.

#-*- vim:ft=sh

enable_respawn_service() (

	grep_q_recursive() {
		local val="$1"
		local file="$2"
		if [ -f "$file" ]; then
			! grep -q "$val" "$file" || return 0
			for f in `sed -n -e "s/^\.include\s//p" $file`; do
				! grep_q_recursive "$val" "$f" || return 0
			done
		fi
		return 1
	}

	[ -n "$1" ] || die "enable_respawn_service: service name not specified"
	local inten="enable automatic respawn for service $1"
	echo_try "$inten"

	local service=$1
	local main_unit=`systemctl show $service | sed -n -e "s/FragmentPath=//p"`
	local respawn_unit="/usr/lib/systemd/system/$service.d/respawn.conf"
	local dropin_units=`systemctl show $service | sed -n -e "s/DropInPaths=//p" | sed "s|$respawn_unit||"`
	local ini="/usr/local/psa/admin/conf/panel.ini"
	local ini_section="systemd"

	local respawn
	[ ! -f "$ini" ] || respawn=`get_ini_conf_var "$ini" "$ini_section" respawn`

	if [ -z "${respawn/on/}" ]; then
		for unit in $main_unit $dropin_units; do
			! grep_q_recursive "^Restart=" 		"$unit" || respawn="off"
			! grep_q_recursive "^Type=oneshot" 	"$unit" || respawn="off"
		done
	fi

	rm -f "$respawn_unit"

	if [ -z "${respawn/on/}" ]; then
		mkdir -p "$(dirname $respawn_unit)"
		if [ -f "$ini" ]; then
			local restart=`		get_ini_conf_var "$ini" "$ini_section" Service.Restart`
			local restartsec=`	get_ini_conf_var "$ini" "$ini_section" Service.RestartSec`
		fi
		cat <<EOT > "$respawn_unit"
[Service]
Restart=${restart:-"on-failure"}
RestartSec=${restartsec:-"5"}
EOT
	fi

	suc
)

selinux_close()
{
	if [ -z "$SELINUX_ENFORCE" -o "$SELINUX_ENFORCE" = "Disabled" ]; then
		return
	fi

	setenforce "$SELINUX_ENFORCE"
}

get_product_versions()
{
	# Don't use global variables set elsewhere in this code. Use substitutions if needed.
	local prod_root_d="/usr/local/psa"

	product_name="psa"

	if [ -z "$product_this_version" ]; then
		# 1. Try to fetch version from file created by bootstrapper (should be 3-component).
		product_this_version="`cat "/var/lock/plesk-target-version" 2>/dev/null`"
		# 2. Fallback to $PRODUCT_ROOT_D/version (should be 3-component).
		if [ -z "$product_this_version" -a -r "$prod_root_d/version" ]; then
			product_this_version="`awk '{ print $1 }' "$prod_root_d/version"`"
		fi
		# 3. Fallback to hardcoded version (2-component). This may cause some other code to fail.
		if [ -z "$product_this_version" ]; then
			product_this_version="18.0"
			echo "Unable to determine \$product_this_version, will use less precise value '$product_this_version'" >&2
		fi
	fi

	product_version="$product_this_version"

	if [ -z "$product_prev_version" ]; then
		if [ -r "$prod_root_d/version.upg" ]; then
			product_prev_version=`awk '{ print $1 }' "$prod_root_d/version.upg"`
		elif [ -r "$prod_root_d/version" ]; then
			product_prev_version=`awk '{ print $1 }' "$prod_root_d/version"`
		else
			product_prev_version="$product_this_version"
		fi
	fi
}

### Copyright 1999-2021. Plesk International GmbH. All rights reserved.

php_module_extract_name()
{
	local config="$1"
	local state="${2:-}"  # "", enabled, disabled
	local short="$3"

	local prefix=""
	[ ! "$state" = "enabled" ] || prefix='^\s*'
	[ ! "$state" = "disabled" ] || prefix='^\s*;\s*'

	local module=$(perl -nle 'print $2 if /'"${prefix}"'(?:zend_|)extension\s*=\s*([\"'"\'"']?)(.*)\.so\1/' "$config")

	if [ -z "$module" -a -n "$short" ]; then
		perl -nle 'print $2 if /'"${prefix}"'(?:zend_|)extension\s*=\s*([\"'"\'"']?)(.*)\1/' "$config"
	else
		echo "$module"
	fi
}

php_module_is_enabled()
{
	local config="$1"
	local ext_s="$2"
	local short="$3"
	php_module_extract_name "$config" 'enabled' "${short}" | grep -q "^$ext_s\$"
}

php_module_is_disabled()
{
	local config="$1"
	local ext_s="$2"
	local short="$3"
	php_module_extract_name "$config" 'disabled' "${short}" | grep -q "^$ext_s\$"
}

php_module_enable()
{
	local config="$1"
	local ext_s="$2"
	local short="$3"

	[ -n "$short" ] || suffix='\.so'

	perl -pi -e 's#^\s*;\s*((?:zend_|)extension\s*=\s*([\"'"\'"']?)'"${ext_s}"''"${suffix}"'\2)#\1#g' "$config"
}

php_module_disable()
{
	local config="$1"
	local ext_s="$2"
	local short="$3"

	[ -n "$short" ] || suffix='\.so'

	perl -pi -e 's#^\s*((?:zend_|)extension\s*=\s*([\"'"\'"']?)'"${ext_s}"''"${suffix}"'\2)#; \1#g' "$config"
}

# vim:ft=sh:
#!/bin/bash
### Copyright 1999-2021. Plesk International GmbH. All rights reserved.
# vim:ft=sh:

option_error()
{
	err "$@"
	err ""
	usage
}

err()
{
	echo "$@" >&2
}

debug()
{
	if [ $_V -ge 1 ]; then
		echo "debug: $*" >&2
	fi
}

usage()
{
cat << EOT >&2
Usage: $prog [OPTIONS]
	-p,--php-cli				Appropriate PHP cli for operations. Mandatory.
	-c,--php-ini				php.ini config for operations. Mandatory.
	-l,--list					Display extensions availiable for load
	-e,--enable=ext				Enable specified extension. Can be specified several times.
	-d,--disable=ext			Disable specified extension. Can be specified several times.
	-v,--verbose				Be more verbose.
	-h,--help					Display this message.
EOT
exit 1
}

get_extension_type()
{
# Check got from ext/standard/dl.c. But may be we should attempt to load via dl or -d
# However, dl can be disabled, and failure of load in -d doesn't cause php to return 1

	local ext_file="$extension_dir/$1.so"

	if readelf -s --wide "$ext_file" | awk '{print $8}' | grep -q -E '^(_|)zend_extension_entry$'; then
		debug "$ext_file: zend_extension detected"
		echo "zend_extension"
		return
	elif readelf -s --wide "$ext_file" | awk '{print $8}' | grep -q -E '^(_|)get_module$'; then
		debug "$ext_file: common_extension detected"
		echo "extension"
		return
	else
		debug "$ext_file: not a php extension"
		echo ""
	fi
}

find_config()
{
	local ext="$1"
	for c in `get_configs`; do
		php_module_extract_name "$c" "" "$shortname_allowed" | xargs -n1 basename | grep -q "^$ext\$" || continue
		echo $c
		return
	done
}

enmod()
{
	local ext="$1"
	if [ -z "$ext" ]; then
		err "empty extension specified"
		return 1
	fi

	local config=$(find_config "$ext")
	local ext_s="$ext"
	local ext_type=$(get_extension_type "$ext")

	if [ -z "$config" ]; then
		err "cannot find config for extension '$ext'"
		return 1
	fi

	if [ "$ext_type" != "extension" -a "$ext_type" != "zend_extension" ]; then
		err "$ext: invalid extension format - not a PHP library"
		return 1
	fi

	if [ "$ext_type" = "zend_extension" ]; then
		ext_s="$extension_dir/${ext}"
	fi

# if extension enabled in config?
	if php_module_is_enabled "$config" "$ext" "$shortname_allowed"; then
		debug "$ext (${ext}.so) already enabled in $config, do nothing"
		return 0
	fi

	if [ "$ext_type" = "zend_extension" ] && php_module_is_enabled "$config" "$ext_s" "$shortname_allowed"; then
		debug "$ext (${ext_s}.so) already enabled in $config, do nothing"
		return 0
	fi

	if php_module_is_disabled "$config" "$ext" "$shortname_allowed"; then
		debug "$ext (${ext}.so) disabled in $config, switch it on"
		php_module_enable "$config" "$ext" "$shortname_allowed"
		return 0
	fi

	if [ "$ext_type" = "zend_extension" ] && php_module_is_disabled "$config" "$ext_s" "$shortname_allowed"; then
		debug "$ext (${ext_s}.so) disabled in $config, switch it on"
		php_module_enable "$config" "$ext_s" "$shortname_allowed"
		return 0
	fi

	debug "$ext is not found in $config, add new line"
	echo "${ext_type}=${ext_s}.so" >> "$config"
	return 0
}

dismod()
{
	local ext="$1"
	if [ -z "$ext" ]; then
		err "empty extension specified"
		return 1
	fi

	local config=$(find_config "$ext")
	local ext_s="$ext"
	local ext_type=$(get_extension_type "$ext")

	if [ -z "$config" ]; then
		err "cannot find config for extension '$ext'"
		return 1
	fi

	if [ "$ext_type" != "extension" -a "$ext_type" != "zend_extension" ]; then
		err "$ext: invalid extension format - not a PHP library"
		return 1
	fi

	if [ "$ext_type" = "zend_extension" ]; then
		ext_s="$extension_dir/${ext}"
	fi

# if extension enabled in config?

	if php_module_is_disabled "$config" "$ext" "$shortname_allowed"; then
		debug "$ext ($ext) already disabled in $config, do nothing"
		return 0
	fi

	if [ "$ext_type" = "zend_extension" ] && php_module_is_disabled "$config" "$ext_s" "$shortname_allowed"; then
		debug "$ext (${ext_s}.so) already disabled in $config, do nothing"
		return 0
	fi

	if php_module_is_enabled "$config" "$ext" "$shortname_allowed"; then
		debug "$ext (${ext}.so) enabled in $config, switch it off"
		php_module_disable "$config" "$ext" "$shortname_allowed"
	fi

	if [ "$ext_type" = "zend_extension" ] && php_module_is_enabled "$config" "$ext_s" "$shortname_allowed"; then
		debug "$ext (${ext_s}.so) enabled in $config, do switch it off"
		php_module_disable "$config" "$ext_s" "$shortname_allowed"
		return 0
	fi

	return 0
}

enable_extensions()
{

	[ -n "$1" ] || return 0

	if check_native_debian_php; then
		$debian_mods_enmod_bin "$@"
		return $?
	fi

	for i in "$@"; do
		if ! enmod $i; then
			err "Cannot enable extension '$i'"
			return 1
		fi
	done
}

disable_extensions()
{
	[ -n "$1" ] || return 0

	if check_native_debian_php; then
		$debian_mods_dismod_bin "$@"
		return $?
	fi

	for i in "$@"; do
		if ! dismod $i; then
			err "Cannot disable extension '$i'"
			return 1
		fi
	done
}

check_native_debian_php()
{

	if [ -n "${debian}" ]; then
		return $debian
	fi

	debian=1

	php_bin="`readlink -e $php_cli`"

	if [ -x "/usr/sbin/php5enmod" -a "$php_bin" = "/usr/bin/php5" ]; then
		debian=0
		debian_mods_availiable_dir="/etc/php5/mods-available"
		debian_mods_enmod_bin="/usr/sbin/php5enmod"
		debian_mods_dismod_bin="/usr/sbin/php5dismod"
		return $debian
	fi

	for ver in 7.0 7.2; do
		if [ -x "/usr/sbin/phpenmod" -a "$php_bin" = "/usr/bin/php$ver" ]; then
			debian=0
			debian_mods_availiable_dir="/etc/php/$ver/mods-available"
			debian_mods_enmod_bin="/usr/sbin/phpenmod"
			debian_mods_dismod_bin="/usr/sbin/phpdismod"
			return $debian
		fi
	done

	return "$debian"
}

get_configs()
{
	if ! check_native_debian_php; then
		_get_configs
		return
	fi

# On debian, we have separate configs for enabled and disabled extensions.
	if [ "$1" = "enabled" ]; then
		_get_configs
		return
	fi

	{
		_get_configs
		ls $debian_mods_availiable_dir/*.ini
	} | xargs -n1 readlink -f | sort -u
}

_get_configs()
{
	$php_cli -c $php_ini -r 'print(php_ini_scanned_files());' | tr ',' '\n' | sort -u | grep -v '^$'
	echo $php_ini
}

have()
{
	if [ -z "$1" ]; then
		err "Error: not enough argument for have function"
		return 1
	fi

	local item=$1
	shift
	for i in "$@"; do
		if [ "$item" = "$i" ]; then
			return 0
		fi
	done
	return 1
}

list_extensions()
{
# First get enabled extensions/zend_extensions
	declare -a got_extensions=()
	local ext configs_enabled
	configs_enabled=$( for c in `get_configs "enabled"`; do
		php_module_extract_name "$c" enabled "$shortname_allowed";
	done )
	for line in $configs_enabled; do
		[ -n "$line" ] || continue
		[ -f "$extension_dir/${line}.so" -o -f "${line}.so" ] || continue
		ext=`basename $line`
		got_extensions+=( $ext )
		echo "$ext on"
	done

# Now get disabled extensions/zend_extensions, need to check existance of file
	for c in `get_configs`; do
		php_module_extract_name "$c" "" "$shortname_allowed";
	done | while read line; do
		[ -n "$line" ] || continue
		[ -f $extension_dir/${line}.so -o -f ${line}.so ] || continue
		have "$(basename $line)" ${got_extensions[*]} && continue || :
		echo "`basename $line` off"
	done
}

prog="`basename $0`"

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
umask 022

TEMP=`getopt -o vhlp:c:e:d: --long help,verbose,php-cli:,php-ini:,list,enable:,disable: \
     -n "$prog" -- "$@"`

if [ $? != 0 ]; then
	echo "Internal Error: getopt cannot parse this command line: $@" >&2
	exit 1
fi

declare -a ext_enable=()
declare -a ext_disable=()
list_cmd=""

_V=0
eval set -- "$TEMP"
while true ; do
	case "$1" in
		-p|--php-cli) php_cli="$2";shift 2;;
		-c|--php-ini) php_ini="$2";shift 2;;
		-e|--enable) ext_enable+=( $2 ); shift 2;;
		-d|--disable) ext_disable+=( $2 ); shift 2;;
		-l|--list) list_cmd="1"; shift;;
		-v|--verbose) let _V++; shift;;
		-h|--help) usage ;;
		--) shift ; break ;;
		*) echo "Unknown option '$1'" ; exit 1 ;;
	esac
done

if [ -z "$php_cli" ]; then
	option_error "No php cli (--php-cli) specified"
fi

if [ ! -x "$php_cli" ]; then
	option_error "PHP cli ($php_cli) should be executeable"
fi

if [ -z "$php_ini" ]; then
	option_error "No php ini (--php-ini) specified"
fi

if [ ! -f "$php_ini" ]; then
	option_error "PHP ini ($php_ini) doesn't exist, or not a file"
fi

extension_dir=$("$php_cli" -c "$php_ini" -r 'print(ini_get("extension_dir"));')

if [ -z "$extension_dir" -o ! -d "$extension_dir" ]; then
	option_error "Extension dir \"$extension_dir\" is empty or not directory"
fi

if [ -z "$list_cmd" -a "${#ext_enable[@]}" -eq 0 -a "${#ext_disable[@]}" -eq 0 ]; then
	option_error "No action specified"
fi

if [ -n "$list_cmd" ] && ! [ "${#ext_enable[@]}" -eq 0 -a "${#ext_disable[@]}" -eq 0 ]; then
	option_error "You cannot use --list and --enable/--disable simultaneously"
fi

phpversion=$("$php_cli" -r 'echo phpversion();')
shortname_allowed=""
case $phpversion in
	[45]*) shortname_allowed="" ;;
	7.0.*) shortname_allowed="" ;;
	7.1.*) shortname_allowed="" ;;
	*) shortname_allowed="1" ;;
esac

if [ -n "$list_cmd" ]; then
	list_extensions
	exit $?
fi

enable_extensions ${ext_enable[*]} && disable_extensions ${ext_disable[*]}
