#!/bin/sh
set -e

print_help_and_exit() {
	echo "Usage: build-deb
create a deb package for this project."
	exit 1
}

build_dest_dir() {
	if [ -z "$DEST" ]; then
		DEST=DEST
	fi
	rm -rf "$DEST"
	mkdir -p "${DEST}${DEST_DIR}"
	for f in Makefile README.rst setup.py requirements*.txt conf $PYTHON_MODULES
	do
		cp -al "$PWD/$f" "${DEST}${DEST_DIR}/$f"
	done
	# in docker based build, wheelhouse/ could be in a different device,
	# can't use hard link.
	cp -ar "$PWD/wheelhouse" "${DEST}${DEST_DIR}/"

	# mkdir -p ${DEST}/etc/systemd/system/
	# cp $PWD/conf/web.service ${DEST}/etc/systemd/system/{{name}}.service

	# if you enable logrotate.conf, remember to choose a good rotate
	# interval and set how many copies to keep.
	# mkdir -p ${DEST}/etc/logrotate.d/
	# cp $PWD/conf/logrotate.conf ${DEST}/etc/logrotate.d/{{name}}

	# nginx site file
	# mkdir -p ${DEST}/etc/nginx/conf.d/
	# cp $PWD/conf/https.site ${DEST}/etc/nginx/conf.d/{{name}}.conf
}

# main()
if [ "$1" = "--help" ]; then
	print_help_and_exit
fi

VERSION=`grep '__version__' {{python-pkg-name}}/__init__.py |cut -d'"' -f 2`
DEB_PKG_NAME="{{name}}"
DEST_DIR="/opt/$DEB_PKG_NAME"
PYTHON_MODULES=`ls */__init__.py|cut -d'/' -f1`

make wheel

build_dest_dir

# add dependencies on libpq5 if you use psycopg2.
fpm -t deb -s dir -n "$DEB_PKG_NAME" -v "$VERSION" -f \
    --depends make \
    -x '*__pycache__' \
    -x '*.pyc' \
    -x '*.pyo' \
    -x '*.deb' \
    --before-install deb-scripts/before-install.sh \
    --after-install deb-scripts/after-install.sh \
    --before-remove deb-scripts/before-remove.sh \
    -C "$DEST" .

# create Dockerfile and .dockerignore file
DEB_PKG="{{name}}_${VERSION}_amd64.deb"
DEPENDS=`dpkg-deb -f "$DEB_PKG" Depends | sed "s/, / /g"`
if ! echo "$DEPENDS" | grep -q python; then
	DEPENDS="$DEPENDS python3"
fi
sed "s/DEB_PKG/$DEB_PKG/; s/DEPENDS/$DEPENDS/" Dockerfile.template > Dockerfile

if [ -e .dockerignore ]; then
	sed -i 2s/'.*'/!$DEB_PKG/ .dockerignore
else
	cat > .dockerignore <<EOF
*
!$DEB_PKG
EOF
fi
