#!/bin/bash

info () {
    echo -e "\033[1m info:   \033[0m $@ ";
}

ok () {
    echo -e "\033[1m done:  \033[0m \033[32m $@ \033[0m";
}

error () {
    echo -e  "\033[1m ERROR:\033[0m \033[31m $@\033[0m";
}

#Check OS version
OsRelease=`cat /etc/system-release`

OsVersion=6
IsOsStream=0
IsOsOracle=0
IsOsAlmaLinux=0

function TestVersion()
{
	local versionStr=$1

	for versionNum in {6..20}
	do
		if [[ $OsRelease == *"${versionStr} ${versionNum}"* ]]; then
			OsVersion=$versionNum
		fi
	done

	if [[ $OsRelease == *"Stream"* ]]; then
    IsOsStream=1
  fi

  if [[ $OsRelease == *"Oracle"* ]]; then
    IsOsOracle=1
  fi

  if [[ $OsRelease == *"AlmaLinux"* ]]; then
    IsOsAlmaLinux=1
  fi

  if [[ $OsRelease == *"VEOS"* ]]; then
        IsVEOS=1
    fi
}

TestVersion "CentOS Linux release"
TestVersion "CentOS Stream release"
TestVersion "Oracle Linux Server release"
TestVersion "Red Hat Enterprise Linux release"
TestVersion "AlmaLinux release"
TestVersion "VEOS release"

if [ "$OsVersion" == 6 ]
then
  error "OS version is not compatible."
  exit
fi

if [ "$OsVersion" == 8 ] || [ "$OsVersion" == 7 ]
then
  if [ "$IsOsStream" == 0 ] && [ "$IsOsOracle" == 0 ] && [ "$IsOsAlmaLinux" == 0 ] && [ "$IsVEOS" == 0 ]
  then
    info "Switching repos for CentOs ${OsVersion}..."
    sed -i -e '/^mirrorlist=http:\/\//d' -e 's/^# *baseurl=http:\/\/mirror.centos.org/baseurl=https:\/\/vault.centos.org/' /etc/yum.repos.d/CentOS-*.repo
  fi
fi

sed -i -e  '/^failovermethod=/d' /etc/yum.repos.d/*.repo

if [ "$OsVersion" == 9 ]
then
  rpm -Uvh https://dl.fedoraproject.org/pub/epel/epel-release-latest-9.noarch.rpm
elif [ "$OsVersion" == 8 ]
then
  rpm -Uvh https://dl.fedoraproject.org/pub/epel/epel-release-latest-8.noarch.rpm
elif [ "$OsVersion" == 7 ]
then
	rpm -Uvh https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm
fi

info "Configuring Clickhouse repos..."

rm -f /etc/yum.repos.d/repo.clickhouse.tech_rpm_stable_x86_64.repo

sudo yum install -y yum-utils
sudo yum-config-manager --add-repo https://packages.clickhouse.com/rpm/clickhouse.repo
sed -i -e 's/repo_gpgcheck=1/repo_gpgcheck=0/g' /etc/yum.repos.d/clickhouse.repo


ok "Finished configuring Clickhouse repos."

info "Configuring vasexperts repos..."

if [ "$OsVersion" == 9 ]
then

  rpm -Uvh http://vasexperts.ru/centos/6/x86_64/vasexperts-repo-1-0.noarch.rpm
  sed -i -e 's/gpgcheck=1/gpgcheck=0/g' /etc/yum.repos.d/vasexperts.repo
  sed -i -e 's,$releasever,8,g' /etc/yum.repos.d/vasexperts.repo

else

  rpm --import http://vasexperts.ru/centos/RPM-GPG-KEY-vasexperts.ru
  rpm -Uvh http://vasexperts.ru/centos/6/x86_64/vasexperts-repo-1-0.noarch.rpm

fi

ok "Finished configuring vasexperts repos."

info "Installing fastor..."

sudo yum install -y fastor

ok "Finished installing fastor."

rm -- "$0"


