#!/bin/sh

#variables
PKGPWD=`pwd`
kver=`uname -r`
install=""
der_ver=1.14.2
patch_ver=2
dist=""

redhat=""
suse=""

#check dist
test -f /etc/redhat-release && redhat="1"
test -f /etc/SuSE-release && suse="1"
test -f /etc/SUSE-brand && suse="1"

#check support in SRPM
cd SRPMS

if [ "$suse" = "1" ]; then
	dist="sles"
	dist_ver=`cat /etc/os-release | grep VERSION_ID | cut -d "=" -f 2 | tr -d '"'`

	echo "ast-drm-$der_ver-$patch_ver-$dist$dist_ver.src.rpm"
	if [ ! -f "ast-drm-$der_ver-$patch_ver-$dist$dist_ver.src.rpm" ]; then
		echo "The distribution is not in SRPMs support list"
		exit 1
	fi

	#Remove previous package
	echo "Check Previous Installation Package ...."
	install=`rpm -qa | grep "ast-drm"`
	if [ "$install" != "" ]; then
		echo "Remove Previous Installation Package, $install"
		rpm -e $install
	fi

	echo "Rebuild SRPM on SUSE Distribution ...."
	rpmbuild --rebuild ast-drm-$der_ver-$patch_ver-$dist$dist_ver.src.rpm
	echo "Install Package on SUSE Distribution ...."
	# Installation has been done in spec

	if [ "$dist_ver" = "15.4" ]; then
		cp /lib/modprobe.d/10-unsupported-modules.conf /etc/modprobe.d/
	fi
	sed -i "s/allow_unsupported_modules 0/allow_unsupported_modules 1/" /etc/modprobe.d/10-unsupported-modules.conf

elif [ "$redhat" = "1" ]; then
	dist=`cat /etc/redhat-release | sed "s/release\ /\\n/g" | sed -n 1p`

	if [[ $dist == CentOS\ Stream* ]]; then
		dist="cent"
		dist_ver=`cat /etc/redhat-release | sed "s/release\ /\\n/g" | sed -n 2p`
	else
		dist="rhel"
		dist_ver=`cat /etc/redhat-release | sed "s/release\ /\\n/g" | sed -n 2p | cut -b 1-3 | cut -c 2 --complement`
	fi

	echo "ast-drm-$der_ver-$patch_ver-$dist$dist_ver.src.rpm"
	if [ ! -f "ast-drm-$der_ver-$patch_ver-$dist$dist_ver.src.rpm" ]; then
		echo "The distribution is not in SRPMs support list"
		exit 1
	fi

	#Remove previous package
	echo "Check Previous Installation Package ...."
	install=`rpm -qa | grep "ast-drm"`
	if [ "$install" != "" ]; then
		echo "Remove Previous Installation Package, $install"
		rpm -e $install
	fi

	echo "Rebuild SRPM on RHEL Distribution ...."
	rpmbuild --rebuild ast-drm-$der_ver-$patch_ver-$dist$dist_ver.src.rpm
	echo "Install Package on RHEL Distribution ...."
	# Installation has been done in spec

else
	echo "Cannot find proper package for this distribution."
	echo "Please update package manually."
fi

cd $PKGPWD

