#!/bin/bash
# SPDX-License-Identifier: AGPL-3.0-or-later
# SPDX-FileCopyrightText: 2021 grommunio GmbH

setup_repo() {
	echo
	echo -e " \x1b[36m▼\x1b[0m grommunio-setup is updating the system"
	echo
	if [ -z "${REPO_USER}" ] || [ -z "${REPO_PASS}" ] ; then
		writelog "No valid subscription credentials provided"
		REPO_PATH="community"
	else
		writelog "Subscription credentials provided: ${REPO_USER}:${REPO_PASS}"
		REPO_PATH="supported"
		curl -Lsk -u "$REPO_USER:$REPO_PASS" "https://download.grommunio.com/RPM-GPG-KEY-grommunio" >/tmp/RPM-GPG-KEY-grommunio
		RETCMD=$?
		if [ ${RETCMD} -ne 0 ]; then
			writelog "Subscription credentials could not be verified, fallback to community repository"
			REPO_PATH="community"
		fi
	fi
	# zypp is abusing query parameters, https://github.com/openSUSE/libzypp/issues/301
	if [ "${REPO_PATH}" = "supported" ]; then
		cat >/etc/zypp/repos.d/grommunio.repo <<EOF
[grommunio]
enabled=1
autorefresh=1
baseurl=https://${REPO_USER}:${REPO_PASS}@download.grommunio.com/${REPO_PATH}/openSUSE_Leap_$(distlevel)/?ssl_verify=no
type=rpm-md
EOF
	else
		curl -Lsk "https://download.grommunio.com/RPM-GPG-KEY-grommunio" >/tmp/RPM-GPG-KEY-grommunio
		mkdir -p /etc/zypp/repos.d
		cat >/etc/zypp/repos.d/grommunio.repo <<EOF
[grommunio]
enabled=1
autorefresh=1
baseurl=https://download.grommunio.com/${REPO_PATH}/openSUSE_Leap_$(distlevel)/?ssl_verify=no
type=rpm-md
EOF
	fi

	rpm --import /tmp/RPM-GPG-KEY-grommunio 2>&1 | tee -a "$LOGFILE"
	zypper --non-interactive refresh 2>&1 | tee -a "$LOGFILE"
	if [ "${PIPESTATUS[0]}" != 0 ]; then
		echo '`zypper ref` returned with non-zero exit status. (No network connection present?)'
		echo "Pausing so you can inspect the log or remedy the issue."
		echo "Hit ENTER when ready to continue g-setup with the next step."
		read yn
	fi
	zypper --non-interactive update 2>&1 | tee -a "$LOGFILE"
	if [ "${PIPESTATUS[0]}" != 0 ]; then
		echo '`zypper up` returned with non-zero exit status.'
		echo "Pausing so you can inspect the log or remedy the issue."
		echo "Hit ENTER when ready to continue g-setup with the next step."
		read yn
	fi
	zypper --non-interactive install -y $PACKAGES 2>&1 | tee -a "$LOGFILE"
	if [ "${PIPESTATUS[0]}" != 0 ]; then
		echo "zypper returned with non-zero exit status."
		echo "Pausing so you can inspect the log or remedy the issue."
		echo "Hit ENTER when ready to continue g-setup with the next step."
		read yn
	fi
	echo
	echo -e " \x1b[36m▼\x1b[0m operation completed"
	echo
	# keep visual output on the screen for a glimpse so admin can decide
	# if the logfile needs to be inspected.
	sleep 1
}
