#!/usr/bin/env bash
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PROJECT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
DIST_DIR="$SCRIPT_DIR"
ARCH=$(dpkg --print-architecture 2>/dev/null || echo "amd64")

# Read version from Cargo.toml
VERSION=$(grep '^version' "$PROJECT_DIR/crates/audiofiles-app/Cargo.toml" | head -1 | sed 's/.*"\(.*\)".*/\1/')
echo "Building AudioFiles v${VERSION} .deb (${ARCH})"

# Step 1: Build release binary
echo "==> Building release binary..."
cd "$PROJECT_DIR"
cargo build --release -p audiofiles-app

# Step 2: Assemble deb tree
echo "==> Assembling package..."
PKG_DIR="$DIST_DIR/.deb-staging/audiofiles_${VERSION}_${ARCH}"
rm -rf "$DIST_DIR/.deb-staging"
mkdir -p "$PKG_DIR/DEBIAN"
mkdir -p "$PKG_DIR/usr/bin"
mkdir -p "$PKG_DIR/usr/share/applications"
mkdir -p "$PKG_DIR/usr/share/icons/hicolor/256x256/apps"

cp "$PROJECT_DIR/target/release/audiofiles-app" "$PKG_DIR/usr/bin/audiofiles-app"
cp "$DIST_DIR/audiofiles.desktop" "$PKG_DIR/usr/share/applications/audiofiles.desktop"
cp "$DIST_DIR/audiofiles.png" "$PKG_DIR/usr/share/icons/hicolor/256x256/apps/audiofiles.png"

# Compute installed size in KB
INSTALLED_SIZE=$(du -sk "$PKG_DIR" | cut -f1)

# Runtime deps:
#   libasound2  - ALSA (cpal audio playback)
#   libgl1      - OpenGL (eframe glow backend)
#   libxcb1     - X11 connection (egui/winit)
#   libxkbcommon0 - Keyboard input
#   libssl3     - TLS (reqwest native-tls) -- libssl3 for Ubuntu 22.04+
#   libgtk-3-0  - File dialogs (rfd/nfd)
cat > "$PKG_DIR/DEBIAN/control" << CONTROL
Package: audiofiles
Version: ${VERSION}
Section: sound
Priority: optional
Architecture: ${ARCH}
Depends: libasound2, libgl1, libxcb1, libxkbcommon0, libssl3, libgtk-3-0
Installed-Size: ${INSTALLED_SIZE}
Maintainer: Maxwell Morgan Johnson <max@makenot.work>
Homepage: https://makenot.work/p/audiofiles
Description: Sample manager with content-addressed storage
 AudioFiles is a desktop sample manager with content-addressed storage,
 virtual filesystem, and cloud sync. Supports WAV, FLAC, MP3, OGG, and
 AIFF formats.
CONTROL

# Step 3: Set permissions
chmod 755 "$PKG_DIR/usr/bin/audiofiles-app"
chmod 644 "$PKG_DIR/usr/share/applications/audiofiles.desktop"
chmod 644 "$PKG_DIR/usr/share/icons/hicolor/256x256/apps/audiofiles.png"

# Step 4: Build .deb
echo "==> Building .deb..."
DEB_NAME="audiofiles_${VERSION}_${ARCH}.deb"
DEB_PATH="$DIST_DIR/$DEB_NAME"
rm -f "$DEB_PATH"

dpkg-deb --build --root-owner-group "$PKG_DIR" "$DEB_PATH"

# Cleanup
rm -rf "$DIST_DIR/.deb-staging"

echo ""
echo "Done: $DEB_PATH"
echo "Install with: sudo dpkg -i $DEB_NAME"
