#!/bin/sh

RUNNING_USER=`whoami`
RUNNING_USER_ID=`id -u $RUNNING_USER`

if [ "$RUNNING_USER_ID" != "0" ]
then
	echo
	echo "This script must be run as root"
	echo
	exit 1
fi

EMS_OS_NAME=`cat /etc/redhat-release|sed "s/\(.*\) release .*/\1/"|sed "s/ //g"|tr "[:upper:]" "[:lower:]"`
EMS_OS_VERSION=`cat /etc/redhat-release|sed "s/.* release \([0-9\.]*\) .*/\1/"|tr "[:upper:]" "[:lower:]"`

# Check if this is a CentOS issue
case "$EMS_OS_NAME" in
  *derivedfromredhatenterpriselinux*)
    EMS_OS_NAME="centos"
    EMS_OS_VERSION=`cat /etc/redhat-release|sed "s/.* Linux \([0-9\.]*\) .*/\1/"|tr "[:upper:]" "[:lower:]"`
    ;;
esac

# Just get the major and minor versions
EMS_OS_VERSION=$( echo "$EMS_OS_VERSION" | cut -d\. -f1,2 )

EMS_BASE_REPO_URL=https://yum171.evostream.com/release/$EMS_OS_NAME/$EMS_OS_VERSION
EMS_REPO_PKG_LIST=$EMS_BASE_REPO_URL/repodata/primary.xml.gz

#echo "EMS_OS_NAME:              $EMS_OS_NAME"
#echo "EMS_OS_VERSION:           $EMS_OS_VERSION"
#echo "EMS_BASE_REPO_URL:        $EMS_BASE_REPO_URL"
#echo "EMS_REPO_PKG_LIST:        $EMS_REPO_PKG_LIST"

which curl >/dev/null 2>&1

if [ "$?" != "0" ]
then
	echo
	echo "curl utility is needed by the installer. Please execute the following command"
	echo
	echo "sudo yum install curl"
	echo
	exit 1
fi

curl "$EMS_REPO_PKG_LIST" -o /tmp/primary.xml.gz >/dev/null 2>&1
if [ "$?" != "0" ]
then
	echo
	echo "Unable to fetch file $EMS_REPO_PKG_LIST"
	echo
	exit 1
fi

gunzip -fq /tmp/primary.xml.gz >/dev/null 2>&1
if [ "$?" != "0" ]
then
	echo
	echo "Unable to unzip /tmp/primary.xml.gz"
	echo
	exit 1
fi

KEYS_PACKAGE=`cat /tmp/primary.xml|grep "location href=\"evostream-keys"| sed "s/.*href=\"\(evostream-keys-.*\.noarch\.rpm\).*/\1/"|sort|tail -1`

rpm -ivh --force "$EMS_BASE_REPO_URL/$KEYS_PACKAGE" >/dev/null 2>&1
if [ "$?" != "0" ]
then
	echo
	echo "Unable to install $EMS_BASE_REPO_URL/$KEYS_PACKAGE"
	echo
	exit 1
fi

# Update the repo as well
sed -i 's/\/\/yum.evostream.com/\/\/yum171.evostream.com/g' /etc/yum.repos.d/evostream.repo

echo "EvoStream keys installed successfully"

