#!/bin/sh

BASEDIR=`pwd`
VERSION=`freebsd-version -u | cut -d '.' -f 1`

USE_OPNSENSE_TOOLS=true

#
# Environment configuration for using USE_OPNSENSE_TOOLS
#
# mkdir -p /tmp/opnsense
# cd /tmp/opnsense
# git clone https://github.com/opnsense/tools
# cd tools
# env ROOTDIR=/tmp/opnsense make update
#

########

if ! test -d opnsense; then
	echo "Cloning ntop/opnsense"
	git clone https://github.com/ntop/opnsense.git
else
	echo "Updating ntop/opnsense"
	cd opnsense; git pull --rebase; cd ${BASEDIR}
fi

#######

# Build package

STAGEDIR=

if [ "$USE_OPNSENSE_TOOLS" = true ] ; then

	# Cloning OPNsense plugins repo
	if ! test -d plugins; then
		echo "Cloning opnsense/plugins"
		git clone https://github.com/opnsense/plugins.git
	else
		echo "Updating opnsense/plugins"
		cd plugins; git pull --rebase; cd ${BASEDIR}
		rm -rf plugins/net/ntopng-enterprise
	fi

	# Copying ntopng plugin
	cp -r opnsense/ntopng/plugins/net/ntopng-enterprise plugins/net/
	cp package/Makefile plugins/net/ntopng-enterprise/

	# Build pkg
	cd plugins/net/ntopng-enterprise
	make package
	cd ${BASEDIR}

	STAGEDIR=${BASEDIR}/plugins/net/ntopng-enterprise/work/src

	# Fix package name
	sed -i '' 's/os-ntopng-enterprise-devel/os-ntopng-enterprise/g' ${STAGEDIR}/+MANIFEST
	sed -i '' 's/os-ntopng-enterprise-devel/os-ntopng-enterprise/g' ${STAGEDIR}/usr/local/opnsense/version/ntopng-enterprise

	# Add ntopng as dependency
	echo "deps: {" >> ${STAGEDIR}/+MANIFEST
	echo "    ntopng: { version: "@PACKAGE_VERSION@", origin: net/ntopng }" >> ${STAGEDIR}/+MANIFEST
	echo "}" >> ${STAGEDIR}/+MANIFEST

else
	STAGEDIR=${BASEDIR}/stage
	rm -rf ${STAGEDIR}
	mkdir -p ${STAGEDIR}

	# Build content

	mkdir -p ${STAGEDIR}/usr/local
	cp -r $BASEDIR/opnsense/ntopng/plugins/net/ntopng-enterprise/src/* ${STAGEDIR}/usr/local/

	# Build plist

	PREFIX_LEN=$(echo ${STAGEDIR} | wc -m)
	find ${STAGEDIR} -type f -follow -print | cut -c ${PREFIX_LEN}- > plist

	mv plist ${STAGEDIR}/

	# +MANIFEST

	cp package/+MANIFEST ${STAGEDIR}/

	# +POST_INSTALL

	cp package/+POST_INSTALL ${STAGEDIR}/
fi

# Package

pkg create -m ${STAGEDIR}/ -r ${STAGEDIR}/ -p ${STAGEDIR}/plist -o .

/bin/rm -f ~/binary_packages/os-ntopng-enterprise-*

if test $VERSION -eq "13" ; then
	tar -tvf os-ntopng-enterprise-@PACKAGE_VERSION@.pkg
else
	tar -tvf os-ntopng-enterprise-@PACKAGE_VERSION@.txz
fi

cp os-ntopng-enterprise-@PACKAGE_VERSION@.* ~/binary_packages/

