function clean() {
	echo 'Cleaning up...'
	rm -rf x/ y/ postinst prerm postrm
	echo 'Done.'
}

if [ "$1" == "clean" ]
then
	clean
	rm -rf RPM
	exit 0
fi

if ! ls DEB | grep -qi deb
then
	echo 'ERROR: Please place a driver file, such as `cx4-linux-graphics-driver-dri-glvnd_26.00.49_amd64.deb`, inside of the DEB/ folder.'
	exit 1
fi

if [ "$VERSION" == "" ]
then
	VERSION=$(ls DEB | xargs | cut -d_ -f2)
	echo 'Using detected version `'$VERSION'`.'
else
	echo 'Using version override `'$VERSION'`.'
fi

rm -rf x/ y/
cat SCRIPTLETS/postinst | sed 's/$VERSION/'$VERSION'/g' > postinst
cat SCRIPTLETS/prerm | sed 's/$VERSION/'$VERSION'/g' > prerm
cat SCRIPTLETS/postrm | sed 's/$VERSION/'$VERSION'/g' > postrm

mkdir -p x/ y/ y/usr/lib64/ y/usr/lib64/xorg/modules/extensions/ y/usr/lib64/xorg/modules/drivers/
dpkg-deb -x DEB/*.deb x
cp -a x/* y/

function import() {
	cd y
	baddr=$1
	raddr=$2
	taddr=$3
	libs="$(ls $baddr/$raddr | xargs) END"
	i=1
	while [ "$(echo -n $libs | cut -d' ' -f$i)" != "END" ]
	do
		olib="$(echo -n $libs | cut -d' ' -f$i)"
		olib=$(realpath $baddr/$raddr)/$olib
		rlib=$(realpath $taddr/$raddr)/$(basename $olib)

		if file $olib | grep -qi directory
		then
			mkdir $rlib
		else
			ln -s $(realpath --relative-to $(dirname $rlib) $olib) $rlib
		fi

		echo -n '.'
		i=$((i+1))
	done
	cd ..
}

echo 'Building symbolic links...'
import usr/lib/x86_64-linux-gnu . usr/lib64
import usr/lib/x86_64-linux-gnu gbm usr/lib64
import usr/lib/x86_64-linux-gnu dri usr/lib64
import usr/lib/x86_64-linux-gnu vdpau usr/lib64
import usr/lib/x86_64-linux-gnu cx4libclc usr/lib64
import usr/lib/x86_64-linux-gnu cx4libclc/clc usr/lib64
import usr/lib/x86_64-linux-gnu cx4libclc/clc/2.0 usr/lib64
import usr/lib/x86_64-linux-gnu cx4libclc/clc/2.0/include usr/lib64
import usr/lib/x86_64-linux-gnu cx4libclc/clc/2.0/lib usr/lib64
import usr/lib/xorg/modules/drivers . usr/lib64/xorg/modules/drivers
import usr/lib/xorg/modules/extensions . usr/lib64/xorg/modules/extensions
echo ''
ln -s $(realpath --relative-to y/usr/lib64/dri/ y/usr/lib/x86_64-linux-gnu/dri/cx4_vndri.so) \
	y/usr/lib64/dri/cx4_dri.so

cat x/usr/share/X11/xorg.conf.d/10-cx4gpu.conf | \
	sed 's/Identifier/Option "GlxVendorLibrary" "cx4"\n    Identifier/' > \
	y/usr/share/X11/xorg.conf.d/10-cx4gpu.conf

cat x/usr/share/glvnd/egl_vendor.d/10_cx4.json | \
	sed 's/""/"libEGL_cx4.so.0"/' > \
	y/usr/share/glvnd/egl_vendor.d/10_cx4.json

cd y
echo 'Building package...'
fpm -s dir -t rpm -n cx4-linux-graphics-driver-dri-glvnd -v $VERSION \
	--after-install ../postinst \
	--before-remove ../prerm \
	--after-remove ../postrm \
	--maintainer "Shanghai Zhaoxin Semiconductor Co., Ltd." \
	--description "Shanghai Zhaoxin Semiconductor Co., Ltd. Graphics drivers" \
	--url "https://www.zhaoxin.com" \
	--prefix / -C . .
cd ..
mkdir -p RPM
mv y/*.rpm RPM/
clean
