#!/bin/bash
set -euo pipefail

VERSION="${VERSION:-$(git describe --tags --always --dirty 2>/dev/null || echo dev)}"
ARCH="${ARCH:-amd64}"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
OUTPUT_DIR="$PROJECT_DIR/dist"
DEB_DIR="$PROJECT_DIR/packaging/debian"

echo "=== Packaging SyncServer v${VERSION} for ${ARCH} ==="

mkdir -p "$OUTPUT_DIR"

DEB_PATH="$OUTPUT_DIR/syncserver_${VERSION}_${ARCH}.deb"

sed "s/@@VERSION@@/${VERSION}/" "$DEB_DIR/DEBIAN/control" > "$DEB_DIR/DEBIAN/control.tmp"
mv "$DEB_DIR/DEBIAN/control.tmp" "$DEB_DIR/DEBIAN/control"

chmod 0755 "$DEB_DIR/DEBIAN/postinst"
chmod 0755 "$DEB_DIR/DEBIAN/prerm"
chmod 0755 "$DEB_DIR/DEBIAN/postrm"
chmod 0644 "$DEB_DIR/DEBIAN/conffiles"
chmod 0644 "$DEB_DIR/etc/syncserver/config.yaml"
chmod 0644 "$DEB_DIR/lib/systemd/system/syncserver.service"

echo "=== Building .deb ==="
dpkg-deb --build --root-owner-group "$DEB_DIR" "$DEB_PATH"

echo "=== Package info ==="
dpkg-deb -I "$DEB_PATH"
echo ""
echo "=== Package contents (first 30) ==="
dpkg-deb -c "$DEB_PATH" | head -30

echo ""
echo "=== Output: $DEB_PATH ==="
