#!/bin/sh
### Copyright 1999-2020. Plesk International GmbH. All rights reserved.

# If env variable PLESK_INSTALLER_ERROR_REPORT=path_to_file is specified then in case of error
# repository_check.sh writes single line json report into it with the following fields:
# - "stage": "repositorycheck"
# - "level": "error"
# - "errtype" is one of the following:
#   * "reponotenabled" - required repository is not enabled.
#   * "configmanagernotinstalled" - dnf config-manager is disabled.
# - "repo": required repository name.
# - "date": time of error occurance ("2020-03-24T06:59:43,127545441+0000")
# - "error": human readable error message.

[ -z "$PLESK_INSTALLER_DEBUG" ] || set -x
[ -z "$PLESK_INSTALLER_STRICT_MODE" ] || set -e

export LC_ALL=C
unset GREP_OPTIONS

SKIP_FLAG="/tmp/plesk-installer-skip-repository-check.flag"
HAS_FATAL_ERRORS=

# @params are tags in format "key=value"
# Report body (human readable information) is read from stdin
# and copied to stderr.
make_error_report()
{
	local report_file="${PLESK_INSTALLER_ERROR_REPORT:-}"

	local python_bin=
	for bin in "/opt/psa/bin/python" "/usr/local/psa/bin/python" "/usr/bin/python2" "/usr/libexec/platform-python" "/usr/bin/python3"; do
		if [ -x "$bin" ]; then
			python_bin="$bin"
			break
		fi
	done

	if [ -n "$report_file" -a -x "$python_bin" ]; then
		"$python_bin" -c 'import sys, json
report_file = sys.argv[1]
error = sys.stdin.read()

sys.stderr.write(error)

data = {
    "error": error,
}

for tag in sys.argv[2:]:
    k, v = tag.split("=", 1)
    data[k] = v

with open(report_file, "a") as f:
    json.dump(data, f)
    f.write("\n")
' "$report_file" "date=$(date --utc --iso-8601=ns)" "$@"
	else
		cat - >&2
	fi
}

report_fatal_no_repo()
{
	local repo="$1"

	make_error_report 'stage=repositorycheck' 'level=error' 'errtype=reponotenabled' "repo=$repo" <<-EOL
		Plesk installation requires '$repo' OS repository to be enabled.
		Make sure it is available and enabled, then try again.
	EOL

	HAS_FATAL_ERRORS="yes"
}

has_dnf_enabled_repo()
{
	local repo="$1"

	# note: --noplugins may cause failure and empty output on RedHat
	dnf repoinfo --enabled --cacheonly -q | egrep -q "^Repo-id\s*: $repo\s*$"
}

check_repos_centos8()
{
	if ! dnf config-manager --help >/dev/null 2>&1 && ! dnf install --disablerepo 'PLESK_*' -q -y 'dnf-command(config-manager)'; then
		make_error_report 'stage=repositorycheck' 'level=error' 'errtype=configmanagernotinstalled' <<-EOL
			Failed to install config-manager dnf plugin.
			Make sure repositories configuration of dnf package manager is correct
			(use 'dnf repolist --verbose' to get its actual state), then try again.
		EOL
		HAS_FATAL_ERRORS="yes"
		return
	fi

	for repo in "PowerTools"; do
		if ! dnf config-manager --set-enabled "$repo"; then
			has_dnf_enabled_repo "$repo" || report_fatal_no_repo "$repo"
		fi
	done
}

check_repos_redhat8()
{
	local arch="`/usr/bin/arch`"

	for repo in "codeready-builder-for-rhel-8-$arch-rpms"; do
		if ! subscription-manager repos --enable "$repo"; then
			has_dnf_enabled_repo "$repo" || report_fatal_no_repo "$repo"
		fi
	done
}

platform()
{
	local distrib="unknown"
	local version=""

	if [ -e /etc/debian_version ]; then
		if [ -e /etc/lsb-release ]; then
			. /etc/lsb-release

			distrib="$DISTRIB_ID"
			version="$DISTRIB_RELEASE"
		else
			distrib="debian"
			version="$(head -n 1 /etc/debian_version)"
		fi
	elif [ -e /etc/redhat-release ]; then
		local header="$(head -n 1 /etc/redhat-release)"

		case "$header" in
			Red\ Hat*)      distrib="redhat" ;;
			CentOS*)        distrib="centos" ;;
			CloudLinux*)    distrib="cloudlinux" ;;
			Virtuozzo*)     distrib="vzlinux" ;;
			*)              distrib="$(echo $header | awk '{ print $1 }')" ;;
		esac

		# Treat CloudLinux and Virtuozzo Linux as CentOS for now
		! [ "$distrib" = "cloudlinux" -o "$distrib" = "vzlinux" ] || distrib="centos"

		version="$(echo $header | sed -e 's/[^0-9]*\([0-9.]*\)/\1/g')"
	fi

	echo "${distrib}${version%%.*}" | tr "[:upper:]" "[:lower:]"
}

check_repos()
{
	local checker="check_repos_`platform`"

	case "`type "$checker" 2>/dev/null`" in
		*function*)
			"$checker" "$@"
			;;
	esac
}

# ---

if [ -f "$SKIP_FLAG" ]; then
	echo "Repository check was skipped due to flag file." >&2
	exit 0
fi

check_repos

[ -z "$HAS_FATAL_ERRORS" ] || exit 2
