#!/bin/sh
#
# Copyright (C) 2012, 2017, 2019  Etersoft
# Copyright (C) 2012, 2017, 2019  Vitaly Lipatov <lav@etersoft.ru>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#

load_helper epm-sh-altlinux

ETERSOFTPUBURL=http://download.etersoft.ru/pub
ALTLINUXPUBURL=http://ftp.altlinux.org/pub/distributions

__epm_addrepo_rhel()
{
	local repo="$*"
	if [ -z "$repo" ] ; then
		echo "Add repo."
		echo "1. Use with repository URL, f.i. http://www.example.com/example.repo"
		echo "2. Use with epel to add EPEL repository"
		echo "3. Use with powertools to add PowerTools repository"
		echo "4. Use with crb to add Rocky Linux CRB repository"
		return 1
	fi
	case "$1" in
		epel)
			# dnf -y install https://dl.fedoraproject.org/pub/epel/epel-release-latest-8.noarch.rpm
			epm install epel-release
			return 1
			;;
		powertools)
			# https://serverfault.com/questions/997896/how-to-enable-powertools-repository-in-centos-8
			epm install --skip-installed dnf-plugins-core
			sudocmd dnf config-manager --set-enabled powertools
			return 1
			;;
		crb)
			# https://wiki.rockylinux.org/rocky/repo/
			epm install --skip-installed dnf-plugins-core
			sudocmd dnf config-manager --set-enabled crb
			return 1
			;;
	esac
	return 0
}

__epm_addrepo_etersoft_addon()
{
	epm install --skip-installed apt-conf-etersoft-common apt-conf-etersoft-hold || fatal
	# TODO: ignore only error code 22 (skipped) || fatal

	local pb="$DISTRVERSION/branch"
	[ "$DISTRVERSION" = "Sisyphus" ] && pb="$DISTRVERSION"

	# FIXME
	[ -n "$DISTRVERSION" ] || fatal "Empty DISTRVERSION"

	# TODO: use apt-repo add ?
	echo "" | sudocmd tee -a /etc/apt/sources.list
	echo "# added with eepm addrepo etersoft" | sudocmd tee -a /etc/apt/sources.list
	echo "rpm [etersoft] $ETERSOFTPUBURL/Etersoft LINUX@Etersoft/$pb/$DISTRARCH addon" | sudocmd tee -a /etc/apt/sources.list
	if [ "$DISTRARCH" = "x86_64" ] ; then
		echo "rpm [etersoft] $ETERSOFTPUBURL/Etersoft LINUX@Etersoft/$pb/x86_64-i586 addon" | sudocmd tee -a /etc/apt/sources.list
	fi
	echo "rpm [etersoft] $ETERSOFTPUBURL/Etersoft LINUX@Etersoft/$pb/noarch addon" | sudocmd tee -a /etc/apt/sources.list
}

__epm_addrepo_altlinux()
{
	local repo="$*"
	local branch="$(echo "$DISTRVERSION" | tr "[:upper:]" "[:lower:]")"
	[ -n "$branch" ] || fatal "Empty DISTRVERSION"

	if [ -z "$repo" ] || [ "$repo" == "--help" ] ; then
		info "Add branch repo. Use follow params:"
		sudocmd apt-repo $dryrun add branch
		echo "etersoft           - for LINUX@Etersoft repo"
		echo "basealt            - for BaseALT repo"
		echo "yandex             - for BaseALT repo mirror on yandex (recommended)"
		echo "<task number>      - add task repo"
		echo "archive 2018/02/09 - for archive from that date"
		echo "autoimports        - for BaseALT autoimports repo"
		return
	fi

	case "$1" in
		etersoft)
			info "add Etersoft's addon repo"
			assure_exists apt-repo
			__epm_addrepo_etersoft_addon
			sudocmd apt-repo add $branch
			epm repofix etersoft
			return 0
			;;
		basealt|ALTLinux|ALTServer)
			# TODO: setrepo?
			assure_exists apt-repo
			sudocmd apt-repo add $branch
			return 0
			;;
		yandex)
			assure_exists apt-repo
			sudocmd apt-repo add $branch
			epm repofix yandex
			return 0
			;;
		autoimports)
			repo="autoimports.$branch"
			;;
		archive)
			datestr="$2"
			echo "$datestr" | grep -Eq "^20[0-2][0-9]/[01][0-9]/[0-3][0-9]$" || fatal "use follow date format: 2017/12/31"

			echo "" | sudocmd tee -a /etc/apt/sources.list
			local distrversion="$(echo "$DISTRVERSION" | tr "[:upper:]" "[:lower:]")"
			local rpmsign='[alt]'
			[ "$distrversion" != "sisyphus" ] && rpmsign="[$distrversion]"
			echo "rpm $rpmsign $ALTLINUXPUBURL archive/$distrversion/date/$datestr/$DISTRARCH classic" | sudocmd tee -a /etc/apt/sources.list
			if [ "$DISTRARCH" = "x86_64" ] ; then
				echo "rpm $rpmsign $ALTLINUXPUBURL archive/$distrversion/date/$datestr/x86_64-i586 classic" | sudocmd tee -a /etc/apt/sources.list
			fi
			echo "rpm $rpmsign $ALTLINUXPUBURL archive/$distrversion/date/$datestr/noarch classic" | sudocmd tee -a /etc/apt/sources.list
			return 0
			;;
	esac

	assure_exists apt-repo

	if tasknumber "$repo" >/dev/null ; then
		sudocmd_foreach "apt-repo $dryrun add" $(tasknumber "$repo")
		return
	fi

	sudocmd apt-repo $dryrun add "$repo"

}

__epm_addkey_altlinux()
{
    local url="$1"
    local fingerprint="$2"
    local comment="$3"

    local name="$(basename "$url" .gpg)"

    [ -s /etc/apt/vendors.list.d/$name.list ] && return

# TODO: get this info from the gpg key
    cat << EOF | sudorun tee /etc/apt/vendors.list.d/$name.list
simple-key "$name" {
        FingerPrint "$fingerprint";
        Name "$comment";
}
EOF
        eget -q -O /tmp/$name.gpg $url || fatal
        sudorun gpg --no-default-keyring --keyring /usr/lib/alt-gpgkeys/pubring.gpg --import /tmp/$name.gpg
        rm -f /tmp/$name.gpg
}

__epm_addkey_deb()
{
    local url="$1"
    local fingerprint="$2"
    local comment="$3"

    local name="$(basename $url .gpg)"

    [ -s /etc/apt/trusted.gpg.d/$name.gpg ] && return

    if [ -z "$fingerprint" ] ; then
        set_sudo
        eget -q -O- "$url" | sudorun apt-key add -
#
#        if [ ! -f /etc/apt/trusted.gpg.d/$name.gpg ]; then
#                epm tool eget -q -O /etc/apt/trusted.gpg.d/$name.gpg https://example.com/$name.gpg > /dev/null
#                chmod 0644 /etc/apt/trusted.gpg.d/$name.gpg
#        fi

        return
    fi
    sudocmd apt-key adv --keyserver "$url" --recv "$fingerprint"
}

epm_addkey()
{

case $BASEDISTRNAME in
	"alt")
		__epm_addkey_altlinux "$@"
		return
		;;
esac

case $PMTYPE in
	apt-dpkg)
		__epm_addkey_deb "$@"
		;;
esac

}

__epm_addrepo_deb()
{
	assure_exists apt-add-repository software-properties-common
	local ad="$($DISTRVENDOR --distro-arch)"
	# TODO: move to distro_info
	local nd="$(lsb_release -cs)"
	local repo="$*"

	if [ -z "$repo" ] || [ "$repo" = "--help" ]; then
		info "Add repo. You can use follow params:"
		echo "  docker - add official docker repo"
		echo "  ppa:<user>/<ppa-name> - add PPA repo"
		echo "  distribution component name"
		echo "  full sources list line"
		echo "  URL version component"
		return
	fi

	if [ "$DISTRNAME" = "AstraLinuxCE" ] || [ "$DISTRNAME" = "AstraLinuxSE" ] ; then
		echo "Use workaround for AstraLinux"
		# aptsources.distro.NoDistroTemplateException: Error: could not find a distribution template for AstraLinuxCE/orel
		echo "" | sudocmd tee -a /etc/apt/sources.list
		echo "$repo" | sudocmd tee -a /etc/apt/sources.list
		return
	fi


	# keywords
	case "$1" in
		docker)
			__epm_addkey_deb https://download.docker.com/linux/$PKGVENDOR/gpg "9DC858229FC7DD38854AE2D88D81803C0EBFCD88"
			repo="https://download.docker.com/linux/$PKGVENDOR $nd stable"
			;;
	esac

	# if started from url, use heroistic
	if echo "$repo" | grep -E -q "^https?://" ; then
		repo="deb [arch=$ad] $repo"
	fi

	if echo "$repo" | grep -q "https://" ; then
		assure_exists /usr/share/doc/apt-transport-https apt-transport-https
		assure_exists /usr/sbin/update-ca-certificates ca-certificates 
	fi

	# FIXME: quotes in showcmd/sudocmd
	showcmd apt-add-repository "$repo"
	sudorun apt-add-repository "$repo"
	info "Check file /etc/apt/sources.list if needed"
}

epm_addrepo()
{
local repo="$*"

case $BASEDISTRNAME in
	"alt")
		# Note! Don't use quotes here
		__epm_addrepo_altlinux $repo
		return
		;;
esac

case $PMTYPE in
	apt-dpkg)
		# Note! Don't use quotes here
		__epm_addrepo_deb $repo
		;;
	aptitude-dpkg)
		info "You need manually add repo to /etc/apt/sources.list (TODO)"
		;;
	yum-rpm)
		assure_exists yum-utils
		__epm_addrepo_rhel "$repo" || return
		sudocmd yum-config-manager --add-repo "$repo"
		;;
	dnf-rpm)
		__epm_addrepo_rhel "$repo" || return
		sudocmd dnf config-manager --add-repo "$repo"
		;;
	urpm-rpm)
		sudocmd urpmi.addmedia "$repo"
		;;
	zypper-rpm)
		sudocmd zypper ar "$repo"
		;;
	emerge)
		sudocmd layman -a "$repo"
		;;
	pacman)
		info "You need manually add repo to /etc/pacman.conf"
		# Only for alone packages:
		#sudocmd repo-add $pkg_filenames
		;;
	npackd)
		sudocmd npackdcl add-repo --url="$repo"
		;;
	winget)
		sudocmd winget source add "$repo"
		;;
	slackpkg)
		info "You need manually add repo to /etc/slackpkg/mirrors"
		;;
	*)
		fatal "Have no suitable command for $PMTYPE"
		;;
esac

}