#!/bin/bash -e
#
# Build a binary .deb package
#
test $(id -u) == "0" || (echo "Run as root" && exit 1) # requires bash -e

#
# The package name
#
name=romp
arch=$(uname -m)

cd $(dirname $0)/..
project_root=$PWD

#
# Create a temporary build directory
#
tmp_dir=/tmp/$name-debbuild
rm -rf $tmp_dir
mkdir -p $tmp_dir

#
# Copy files
#
mkdir -p $tmp_dir/etc/romp $tmp_dir/var/log/romp $tmp_dir/etc/init.d/ $tmp_dir/usr/sbin/ $tmp_dir/usr/share/man/man1
cp conf/dist/*  $tmp_dir/etc/romp/
cp deploy/init.d/romp $tmp_dir/etc/init.d/
cp target/release/romp $tmp_dir/usr/sbin/
cp deploy/man/romp.1 $tmp_dir/usr/share/man/man1/

VERSION=$(grep "version = " ./Cargo.toml | tr -d 'a-z ="')
sed -e "s/@PACKAGE_VERSION@/$VERSION/" $project_root/deploy/DEBIAN/control.in > $project_root/deploy/DEBIAN/control

size=$(du -sk $tmp_dir | cut -f 1)
sed -i -e "s/@SIZE@/$size/" $project_root/deploy/DEBIAN/control

cp --archive -R $project_root/deploy/DEBIAN $tmp_dir/

#
# setup conffiles
#
(
  cd $tmp_dir/
  find etc -type f | sed 's.^./.' > DEBIAN/conffiles
)

#
# Setup the installation package ownership here if it needs root
#
chown -R root.root $tmp_dir/

#
# Build the .deb
#
dpkg-deb --build $tmp_dir target/$name-$VERSION-1.$arch.deb

test -f target/$name-$VERSION-1.$arch.deb

echo "built target/$name-$VERSION-1.$arch.deb"

if [ -n "$SUDO_USER" ]
then
  chown $SUDO_USER target/$name-$VERSION-1.$arch.deb
fi

# rm -rf $tmp_dir
