#!/bin/sh

#variables
PKGPWD=`pwd`
kver=`uname -r`
install=""
der_ver=1.13.2
patch_ver=0
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

	#start to install
	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 ...."
	rpm -ivh /usr/src/packages/RPMS/ast-drm.$der_ver.$patch_ver.rpm --force
	echo "Rebuilt Image ...."
	dracut -f
	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
	echo "Install Package Ready and Please Reboot System!!"

elif [ "$redhat" = "1" ]; then
	dist="rhel"
	dist_ver=`cat /etc/redhat-release | sed "s/release\ /\\n/g" | sed -n 2p | cut -b 1-3 | cut -c 2 --complement`

	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

	#start to install
	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 ...."
	rpm -ivh /root/rpmbuild/RPMS/ast-drm.$der_ver.$patch_ver.rpm --force
	echo "Rebuilt Image ...."
	dracut -f
	echo "Install Package Ready and Please Reboot System!!"

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

cd $PKGPWD

