#!/bin/bash

PROGNAME="${BASH_SOURCE[0]}"
HERE="$(cd "$(dirname "$PROGNAME")" &>/dev/null && pwd)"
READIES=$(cd $HERE/.. && pwd)
. $READIES/shibumi/defs

#----------------------------------------------------------------------------------------------

# Distributions: 
# centos:7, (quay.io/centos/centos:stream8), (quay.io/centos/centos:stream9)
# rockylinux:8, rockylinux:9, (almalinux:8), (almalinux:9)
# oraclelinux:7, oraclelinux:8, oraclelinux:9
# amazonlinux:2, amazonlinux:2022, amazonlinux:202

# EPEL          https://docs.fedoraproject.org/en-US/epel
# raven         https://rhel.pkgs.org/9/raven-x86_64/
# powertools    https://wiki.rockylinux.org/rocky/repo
# crb           https://wiki.rockylinux.org/rocky/repo
# REMI
# SCL           https://wiki.centos.org/AdditionalResources/Repositories/SCL
#               https://github.com/sclorg/centos-release-scl
#               https://developers.redhat.com/products/red-hat-software-collections/overview
# SCL/ol        https://docs.oracle.com/en/operating-systems/oracle-linux/scl-user/#Oracle-Linux

#             centos7  centos8  centos9  rocky8  rocky9  ubi9  ol7  ol8  ol9  amzn2  amzn2022  amzn2023
# EPEL        v        v        v        v       v       v     v    v    v    v      -         -
# raven       -        v        v        v       v       v     -    v    v    -      v         v
# powertools  v        v        -        v       -       -     -    -    -    -      -         -
# crb         -        -        v        -       v       v*    -    -    -    -      -         -
# REMI        v        v        v        v       v       v     v    v    v    v      -         -
# SCL         v        -        -        -       -       -     v*   -    -    v      -         -

# Notes:
# - rockylinux and almalinux are compatible
# - Rocky Linux repos (https://wiki.rockylinux.org/rocky/repo):
#   baseos, appstream, powertools(8), crb(9), highavailibility, resilientstorage
# - for Oracle Linux 7. SCL/ol should be used instead of SCL
# - ubi9 uses rocky9's repos (baseos, appstream, crb)

# Useful commands and locations:
# dnf repolist [--all]
# dnf groupinfo GROUP
# dnf info PACKAGE
# dnf makecache
# /etc/yum.repos.d

#----------------------------------------------------------------------------------------------

install_raven() {
	# enable raven repo (i.e. pkgs.org)
	if (( EPEL < 8 )) || [[ $arch != x86_64 ]] || (( NO_RAVEN == 1 )); then
		return
	fi

	# the following may be broken due to CA certificates problems:
	xinstall https://pkgs.dyn.su/el${EPEL}/base/x86_64/raven-release.el${EPEL}.noarch.rpm
	
	# jun-2023: workaround for raven CA certificates problems - remove when resolved
	# $READIES/bin/getget
	# runn @ <<-EOF
	# 	wget --no-check-certificate -O /tmp/raven-release-1.0-5.el8.noarch.rpm https://pkgs.dyn.su/el8/base/x86_64/raven-release-1.0-5.el8.noarch.rpm
	# 	xinstall /tmp/raven-release-1.0-5.el8.noarch.rpm
	# 	rm -f /tmp/raven-release-1.0-5.el8.noarch.rpm
	# 	EOF
	# dnf $SUDO config-manager --save --setopt=raven.sslverify=false
	# dnf $SUDO config-manager --save --setopt=raven-modular.sslverify=false
	# dnf $SUDO config-manager --save --setopt=raven-multimedia.sslverify=false
}

install_scl() {
	if (( EPEL > 7 )); then
		return
	fi

	if [[ $osver == amzn2 ]]; then
		runn $SUDO yum-config-manager -y --enable rhel-server-rhscl-7-rpms

		xinstall http://vault.centos.org/centos/7/extras/x86_64/Packages/centos-release-scl-rh-2-3.el7.centos.noarch.rpm || true
		xinstall http://vault.centos.org/centos/7/extras/x86_64/Packages/centos-release-scl-2-3.el7.centos.noarch.rpm || true
		return
	fi

	if [[ $osver == ol7* ]]; then
		runn $SUDO yum-config-manager --enable ol7_software_collections
		runn $SUDO yum-config-manager --enable ol7_latest ol7_optional_latest
		xinstall scl-utils
		xinstall oracle-softwarecollection-release-el7
		return
	fi

	xinstall sudo
	xinstall centos-release-scl
	runn $SUDO yum-config-manager -y --enable rhel-server-rhscl-7-rpms
}

install_remi() {
	if [[ $os != ol ]]; then
		return
	fi
	if [[ $arch == aarch64 ]]; then
		if (( EPEL < 9 )); then
			echo "REMI: does not support aarch64"
			return
		fi
	fi

	if ! rpm -q remi-release &> /dev/null; then
		xinstall http://rpms.remirepo.net/enterprise/remi-release-${EPEL}.rpm
	else
		echo "REMI: already installed"
	fi
	if is_command dnf; then
		runn $SUDO dnf config-manager -y --set-enabled remi
	elif is_command yum; then
		runn $SUDO yum-config-manager -y --enable remi
	fi
}

# As redhat/ubi lack full non-commercial package repos, we use the ones provided by rocky linux
# Rocky epo configuration is from rockylinux:9 image (/etc/yum.repos.d/rocky.repo, rocky-extras.repo),
# with slight modifications (esp. adding rocky- prefix).
# Repo priority is set to 100 in hope to avoid collisions with ubi9 repos, not sure it is effective.
# Repo signature file is also taken from rockylinux:9.

install_rocky_repos() {
	if [[ $osver != rhel9* ]]; then
		return
	fi
	# check whether rhel repos are in place
	if dnf info bison &> /dev/null; then
		return
	fi

	tmp_yumd=$(mktemp -d)
	cat <<-'END' > $tmp_yumd/rocky.repo
		[rocky-baseos]
		name=Rocky Linux $releasever - BaseOS
		mirrorlist=https://mirrors.rockylinux.org/mirrorlist?arch=$basearch&repo=BaseOS-$releasever
		#baseurl=http://dl.rockylinux.org/$contentdir/$releasever/BaseOS/$basearch/os/
		gpgcheck=1
		enabled=1
		countme=1
		metadata_expire=6h
		gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-Rocky-9
		priority=100

		[rocky-appstream]
		name=Rocky Linux $releasever - AppStream
		mirrorlist=https://mirrors.rockylinux.org/mirrorlist?arch=$basearch&repo=AppStream-$releasever
		#baseurl=http://dl.rockylinux.org/$contentdir/$releasever/AppStream/$basearch/os/
		gpgcheck=1
		enabled=1
		countme=1
		metadata_expire=6h
		gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-Rocky-9
		priority=100
		
		[crb]
		name=Rocky Linux $releasever - CRB
		mirrorlist=https://mirrors.rockylinux.org/mirrorlist?arch=$basearch&repo=CRB-$releasever
		#baseurl=http://dl.rockylinux.org/$contentdir/$releasever/CRB/$basearch/os/
		gpgcheck=1
		enabled=1
		countme=1
		metadata_expire=6h
		gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-Rocky-9
		priority=100
		
		[rocky-extras]
		name=Rocky Linux $releasever - Extras
		mirrorlist=https://mirrors.rockylinux.org/mirrorlist?arch=$basearch&repo=extras-$releasever
		#baseurl=http://dl.rockylinux.org/$contentdir/$releasever/extras/$basearch/os/
		gpgcheck=1
		enabled=1
		countme=1
		metadata_expire=6h
		gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-Rocky-9
		priority=100
		END

	cat <<-'END' > $tmp_yumd/RPM-GPG-KEY-Rocky-9
		-----BEGIN PGP PUBLIC KEY BLOCK-----
		Version: resf.keykeeper.v1
		Comment: Keykeeper

		xsFNBGJ5RksBEADF/Lzssm7uryV6+VHAgL36klyCVcHwvx9Bk853LBOuHVEZWsme
		kbJF3fQG7i7gfCKGuV5XW15xINToe4fBThZteGJziboSZRpkEQ2z3lYcbg34X7+d
		co833lkBNgz1v6QO7PmAdY/x76Q6Hx0J9yiJWd+4j+vRi4hbWuh64vUtTd7rPwk8
		0y3g4oK1YT0NR0Xm/QUO9vWmkSTVflQ6y82HhHIUrG+1vQnSOrWaC0O1lqUI3Nuo
		b6jTARCmbaPsi+XVQnBbsnPPq6Tblwc+NYJSqj5d9nT0uEXT7Zovj4Je5oWVFXp9
		P1OWkbo2z5XkKjoeobM/zKDESJR78h+YQAN9IOKFjL/u/Gzrk1oEgByCABXOX+H5
		hfucrq5U3bbcKy4e5tYgnnZxqpELv3fN/2l8iZknHEh5aYNT5WXVHpD/8u2rMmwm
		I9YTEMueEtmVy0ZV3opUzOlC+3ZUwjmvAJtdfJyeVW/VMy3Hw3Ih0Fij91rO613V
		7n72ggVlJiX25jYyT4AXlaGfAOMndJNVgBps0RArOBYsJRPnvfHlLi5cfjVd7vYx
		QhGX9ODYuvyJ/rW70dMVikeSjlBDKS08tvdqOgtiYy4yhtY4ijQC9BmCE9H9gOxU
		FN297iLimAxr0EVsED96fP96TbDGILWsfJuxAvoqmpkElv8J+P1/F7to2QARAQAB
		zU9Sb2NreSBFbnRlcnByaXNlIFNvZnR3YXJlIEZvdW5kYXRpb24gLSBSZWxlYXNl
		IGtleSAyMDIyIDxyZWxlbmdAcm9ja3lsaW51eC5vcmc+wsGKBBMBCAA0BQJieUZL
		FiEEIcslauFvxUxuZSlJcC1CbTUNJ10CGwMCHgECGQEDCwkHAhUIAxYAAgIiAQAK
		CRBwLUJtNQ0nXWQ5D/9472seOyRO6//bQ2ns3w9lE+aTLlJ5CY0GSTb4xNuyv+AD
		IXpgvLSMtTR0fp9GV3vMw6QIWsehDqt7O5xKWi+3tYdaXRpb1cvnh8r/oCcvI4uL
		k8kImNgsx+Cj+drKeQo03vFxBTDi1BTQFkfEt32fA2Aw5gYcGElM717sNMAMQFEH
		P+OW5hYDH4kcLbtUypPXFbcXUbaf6jUjfiEp5lLjqquzAyDPLlkzMr5RVa9n3/rI
		R6OQp5loPVzCRZMgDLALBU2TcFXLVP+6hAW8qM77c+q/rOysP+Yd+N7GAd0fvEvA
		mfeA4Y6dP0mMRu96EEAJ1qSKFWUul6K6nuqy+JTxktpw8F/IBAz44na17Tf02MJH
		GCUWyM0n5vuO5kK+Ykkkwd+v43ZlqDnwG7akDkLwgj6O0QNx2TGkdgt3+C6aHN5S
		MiF0pi0qYbiN9LO0e05Ai2r3zTFC/pCaBWlG1ph2jx1pDy4yUVPfswWFNfe5I+4i
		CMHPRFsZNYxQnIA2Prtgt2YMwz3VIGI6DT/Z56Joqw4eOfaJTTQSXCANts/gD7qW
		D3SZXPc7wQD63TpDEjJdqhmepaTECbxN7x/p+GwIZYWJN+AYhvrfGXfjud3eDu8/
		i+YIbPKH1TAOMwiyxC106mIL705p+ORf5zATZMyB8Y0OvRIz5aKkBDFZM2QN6A==
		=PzIf
		-----END PGP PUBLIC KEY BLOCK-----
		END

	runn $SUDO mv $tmp_yumd/rocky.repo /etc/yum.repos.d/
	runn $SUDO mv $tmp_yumd/RPM-GPG-KEY-Rocky-9 /etc/pki/rpm-gpg/
	runn rm -rf $tmp_yumd
	runn $SUDO dnf makecache
}

install_centos_stream_repos() {
	if [[ $osver != rocky8* && $osver != alamlinux8* ]]; then
		return
	fi

	tmp_yumd=$(mktemp -d)
	cat <<-'END' > $tmp_yumd/CentOS-Stream-AppStream.repo
		[centos-appstream]
		name=CentOS Stream 8 - AppStream
		mirrorlist=http://mirrorlist.centos.org/?release=8-stream&arch=$basearch&repo=AppStream&infra=$infra
		gpgcheck=0
		enabled=1
		priority=100
		END
	runn $SUDO mv $tmp_yumd/CentOS-Stream-AppStream.repo /etc/yum.repos.d/
	runn rm -rf $tmp_yumd
	runn $SUDO dnf makecache
}

#----------------------------------------------------------------------------------------------

if [[ $1 == --help || $1 == help || $HELP == 1 ]]; then
	cat <<-'END'
		Install RHEL-compatible semi-official repositories (EPEL, Raven)

		[ARGVARS...] getepel [--help|help]

		Argument variables:
		EPEL=ver     EPEL version (7/8/9)
		NO_RAVEN=1   Do not install Raven repo

		VERBOSE=1    Print commands
		NOP=1        Print commands but do not execute

		END
	exit 0
fi

#----------------------------------------------------------------------------------------------

os="$(source /etc/os-release; echo $ID;)"
osverid="$(source /etc/os-release; echo "${VERSION_ID}")"
osver="$(source /etc/os-release; echo "${ID}${VERSION_ID}")"
arch=$(uname -m)

if [[ $os == fedora ]]; then
	exit 0
fi

if [[ ! -f /etc/redhat-release && $os != amzn ]]; then
	eprint "Not an EPEL-compatible OS."
	exit 1
fi

if [[ -z $EPEL ]]; then
	if [[ $os != amzn* ]]; then
		EPEL="$(source /etc/os-release; echo $VERSION_ID;)"
	elif [[ $os == fedora ]]; then
		EPEL=9
	elif [[ $osver == amzn2 ]]; then
		EPEL=7
	elif [[ $osver == amzn2022 ]]; then
		EPEL=8
	elif [[ $osver == amzn2023 ]]; then
		EPEL=9
	fi
fi
[[ $EPEL == 7* ]] && EPEL=7
[[ $EPEL == 8* ]] && EPEL=8
[[ $EPEL == 9* ]] && EPEL=9
if [[ $EPEL != 7 && $EPEL != 8 && $EPEL != 9 ]]; then
	eprint "Cannot determine EPEL version."
	exit 1
fi

#----------------------------------------------------------------------------------------------

if [[ $os == ol ]]; then
	if [[ $EPEL == 7 ]]; then
		baseurl="https://yum.oracle.com/repo/OracleLinux/OL${EPEL}/developer_EPEL/\$basearch/"
	else
		baseurl="https://yum.oracle.com/repo/OracleLinux/OL${EPEL}/developer/EPEL/\$basearch/"
	fi
	repo_tmp=$(mktemp /tmp/ol-epel.repo.XXXXXX)
    cat <<-EOF > $repo_tmp
		[ol${EPEL}_developer_EPEL]
		name= Oracle Linux \$releasever EPEL (\$basearch)
		baseurl=${baseurl}
		gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-oracle
		gpgcheck=1
		enabled=1
		EOF
	runn $SUDO mv $repo_tmp /etc/yum.repos.d/ol${EPEL}-epel.repo
    runn $SUDO yum makecache

	install_scl
	install_raven
    exit 0
fi

#----------------------------------------------------------------------------------------------

if [[ $osver == amzn2 ]]; then
	xinstall yum-utils
	runn $SUDO PYTHON=python2 amazon-linux-extras install -y epel

	install_remi
	install_scl
	exit 0
fi

#----------------------------------------------------------------------------------------------

if is_command dnf; then
	xinstall dnf-plugins-core

	if [[ $os != amzn* ]]; then
		(( EPEL < 9 )) && runn $SUDO dnf config-manager -y --set-enabled powertools
		(( EPEL > 8 )) && [[ $os != rhel ]] && runn $SUDO dnf config-manager -y --set-enabled crb

		if [[ $os == rhel* ]]; then
			install_rocky_repos
		fi
		xinstall epel-release
		# xinstall --allowerasing https://dl.fedoraproject.org/pub/epel/epel-release-latest-${EPEL}.noarch.rpm
	fi

	# install_raven comments:
	# The URL https://pkgs.dyn.su/el${EPEL}/base/x86_64/raven-release.el${EPEL}.noarch.rpm is no longer available.
	# We may need to find an alternative source. However, for the context of JSONHDT, it is not needed.
	# Therefore, it has been commented out
	# install_raven
	install_remi
	# install_centos_stream_repos
	
elif is_command yum; then
	xinstall -y yum-utils
	
	xinstall epel-release
	install_scl
	install_remi
fi
