.if !defined(LOCALBASE)
LOCALBASE=	/usr/local
.endif

SUBDIR= 	libGL		\
		libnvidia-tls	\
		libnvidia-cfg	\
		libnvidia-glcore	\
		libvdpau_nvidia	\
		libXvMCNVIDIA

FIND_DIRS=	/usr/lib	\
		${LOCALBASE}/lib

.if exists(/compat/linux)
SUBDIR+=	compat
FIND_DIRS+=	/compat/linux/lib \
		/compat/linux/usr/lib \
		/compat/linux/usr/X11R6/lib
.endif

FIND_FILES!=(find ${FIND_DIRS} \
		-name libGL.a\* -or \
		-name libGL.so\* -or \
		-name libnvidia-tls.so\* -or \
		-name libnvidia-cfg.so\* -or \
		-name libnvidia-glcore.\* -or \
		-name libvdpau\* -or \
		-name libXvMCNVIDIA.\* -or \
		-name libglx.\* \
		| xargs ${ECHO})
DATE=`date "+%Y%m%d"`

GREP=/usr/bin/grep
ECHO=/usr/bin/true

beforeinstall:
	@-for __file in ${FIND_FILES}; do \
		${ECHO} "===> Checking file: $${__file}" ; \
		if [ -L $${__file} ] ; then \
			${ECHO} "	- File is a symlink, removing." ; \
			rm -f $${__file} ; \
			continue ; \
		fi ; \
		if [ ! -e $${__file} ] ; then \
			${ECHO} "	- File does not exist." ; \
			continue ; \
		fi ; \
		${GREP} 'nvidia id:' $${__file} > /dev/null 2>&1 ; RESULT=$$? ; \
		${ECHO} $${__file} | ${GREP} libXvMCNVIDIA > /dev/null 2>&1 ; RESULT2=$$? ; \
		if [ $${RESULT2} -eq 0 ] ; then \
			RESULT=0 ; \
		fi ; \
		if [ $${RESULT} -eq 0 ] ; then \
			${ECHO} "	- File has NVIDIA signature, removing." ; \
			rm -f $${__file} ; \
			continue ; \
		fi ; \
		SUFFIX=`pkg_info -qW $${__file}` ; RESULT=$$? ; \
		if [ -n "$${SUFFIX}" ] ; then \
			${ECHO} "	- File was installed by package $${SUFFIX}" ; \
		else \
			${ECHO} "	- File is unknown or orphaned." ; \
			SUFFIX="orig-${DATE}" ; \
		fi ; \
		${ECHO} "	- Creating backup." ; \
		FILE_NAME=`basename $${__file}` ; \
		DIR_NAME=`dirname $${__file}` ; \
		mv -f $${__file} $${DIR_NAME}/XXX-$${FILE_NAME}.%%.$${SUFFIX} ; \
	done

.include <bsd.subdir.mk>
