#!/usr/bin/env bash
# Build Ubuntu/Debian .deb package (amd64).
set -euo pipefail

VERSION="${1:-2.0.0}"
ARCH_DEB="amd64"

ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
DEB_DIR="$ROOT/dist/deb"
PKG_ROOT="$DEB_DIR/pkg"
PAYLOAD_DIR="$ROOT/dist/release/payload/linux-x64"

cd "$ROOT"

bash installer/linux/build-payload.sh "$VERSION" linux-x64

rm -rf "$PKG_ROOT"
mkdir -p "$PKG_ROOT/DEBIAN"
mkdir -p "$PKG_ROOT/opt/siraya/printer"

cp -a "$PAYLOAD_DIR/app/." "$PKG_ROOT/opt/siraya/printer/"
mkdir -p "$PKG_ROOT/opt/siraya/printer/runtime"
cp "$PAYLOAD_DIR/runtime/node" "$PKG_ROOT/opt/siraya/printer/runtime/node"
chmod +x "$PKG_ROOT/opt/siraya/printer/runtime/node"

cp installer/linux/deb/DEBIAN/postinst "$PKG_ROOT/DEBIAN/postinst"
cp installer/linux/deb/DEBIAN/prerm "$PKG_ROOT/DEBIAN/prerm"
cp installer/linux/deb/DEBIAN/postrm "$PKG_ROOT/DEBIAN/postrm"
chmod 755 "$PKG_ROOT/DEBIAN/postinst" "$PKG_ROOT/DEBIAN/prerm" "$PKG_ROOT/DEBIAN/postrm"

sed "s/^Version:.*/Version: $VERSION/" installer/linux/deb/DEBIAN/control >"$PKG_ROOT/DEBIAN/control"

OUTPUT="$DEB_DIR/siraya-printer_${VERSION}_${ARCH_DEB}.deb"
mkdir -p "$DEB_DIR"
dpkg-deb --root-owner-group --build "$PKG_ROOT" "$OUTPUT"

echo ""
echo "Built: $OUTPUT"
echo "Install: sudo dpkg -i $OUTPUT"
echo "         sudo apt-get install -f   # if dependencies missing"
