#!/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

if [ -f /etc/lsb-release ]
then
	EMS_OS_NAME=`cat /etc/lsb-release|grep "DISTRIB_ID"|cut -d "=" -f2|tr "[:upper:]" "[:lower:]"`
	EMS_OS_VERSION=`cat /etc/lsb-release|grep "DISTRIB_RELEASE"|cut -d "=" -f2|tr "[:upper:]" "[:lower:]"`
elif [ -f /etc/os-release ]
then
	EMS_OS_NAME=`cat /etc/os-release|grep "^ID"|cut -d "=" -f2|tr "[:upper:]" "[:lower:]"`
	EMS_OS_VERSION=`cat /etc/os-release|grep "VERSION_ID"|cut -d "\"" -f2|tr "[:upper:]" "[:lower:]"`
elif [ -f /etc/debian_version ]
then
	EMS_OS_NAME=debian
	EMS_OS_VERSION=`cat /etc/debian_version`
else
	echo
	echo "Operating system not recognized"
	echo
	exit 1
fi


EMS_BASE_REPO_URL=http://oldapt.evostream.com/release/$EMS_OS_NAME/$EMS_OS_VERSION
EMS_REPO_PKG_LIST=$EMS_BASE_REPO_URL/dists/evostream/main/binary-i386/Packages

#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 wget >/dev/null 2>&1

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

wget "$EMS_REPO_PKG_LIST" -O /tmp/Packages >/dev/null 2>&1
if [ "$?" != "0" ]
then
	echo
	echo "Unable to fetch file $EMS_REPO_PKG_LIST"
	echo
	exit 1
fi

KEYS_PACKAGE=$EMS_BASE_REPO_URL/`cat /tmp/Packages |grep "Filename: "|grep "evostream-keys"|cut -d " " -f2`

wget "$KEYS_PACKAGE" -O /tmp/keys.deb >/dev/null 2>&1
if [ "$?" != "0" ]
then
	echo
	echo "Unable to fetch file $KEYS_PACKAGE"
	echo
	exit 1
fi

dpkg -i /tmp/keys.deb >/dev/null 2>&1
if [ "$?" != "0" ]
then
	echo
	echo "Unable to install package /tmp/keys.deb"
	echo
	exit 1
fi

# Update the repo as well
sed -i 's/\/\/apt.evostream.com/\/\/oldapt.evostream.com/g' /etc/apt/sources.list.d/evostream.list

apt-get update >/dev/null 2>&1
if [ "$?" != "0" ]
then
	echo
	echo "Unable to perform apt-get update"
	echo
	exit 1
fi

echo "EvoStream keys installed successfully"

