# Maintainer: nimbt <niko@n1kt.ru>
# Для разработки: nimble build && sudo cp nbt nimbt-daemon /usr/bin/
pkgname=nimbt
pkgver=0.1.0
pkgrel=3
pkgdesc="Lightweight Bluetooth manager for Linux (daemon + CLI)"
arch=('x86_64' 'aarch64')
url="https://git.n1kt.ru/Niko/nim-bt"
license=('MIT')
depends=('dbus' 'glibc')
makedepends=('nim' 'nimble')
source=("$pkgname-$pkgver.tar.gz::https://git.n1kt.ru/Niko/nim-bt/archive/v$pkgver.tar.gz")
sha256sums=('SKIP')

_repodir=nim-bt

prepare() {
  cd "$srcdir/$_repodir"
  nimble install -y --depsOnly --nimbleDir:"$srcdir/nimble" || true
}

patch_dbus() {
  local NIMBLE_DIR="$srcdir/nimble"
  local dbus_dir="$NIMBLE_DIR/pkgs2/$(ls "$NIMBLE_DIR/pkgs2" 2>/dev/null | grep '^dbus-')"
  if [ -z "$dbus_dir" ] || [ ! -f "$dbus_dir/dbus/private/value.nim" ]; then
    echo "ERROR: nim-dbus not found in $NIMBLE_DIR/pkgs2/"
    exit 1
  fi
  if grep -q 'addr val.uint32Value' "$dbus_dir/dbus/private/value.nim" 2>/dev/null; then
    echo "nim-dbus already patched"
  else
    patch -d "$dbus_dir" -p1 < "$srcdir/$_repodir/nim-dbus-dtbool.patch" && \
      echo "Patched nim-dbus: added dtBool to getPrimitive" || \
      echo "ERROR: failed to patch nim-dbus"
  fi
}

build() {
  cd "$srcdir/$_repodir"
  export NIMBLE_DIR="$srcdir/nimble"
  patch_dbus
  rm -rf "$srcdir/nimcache"
  nim c \
    --noNimblePath \
    --nimblePath:"$NIMBLE_DIR/pkgs2" \
    --nimcache:"$srcdir/nimcache" \
    --mm:orc -d:release --opt:speed --hints:off \
    -o:build/nbt src/nbt.nim
  nim c \
    --noNimblePath \
    --nimblePath:"$NIMBLE_DIR/pkgs2" \
    --nimcache:"$srcdir/nimcache" \
    --mm:orc -d:release --opt:speed --hints:off \
    -o:build/nimbt-daemon src/nimbt_daemon.nim
}

package() {
  cd "$srcdir/$_repodir"
  install -Dm755 build/nbt "$pkgdir/usr/bin/nbt"
  install -Dm755 build/nimbt-daemon "$pkgdir/usr/bin/nimbt-daemon"
  install -Dm644 LICENSE "$pkgdir/usr/share/licenses/$pkgname/LICENSE"
  install -Dm644 nimbt-daemon.service "$pkgdir/usr/lib/systemd/user/nimbt-daemon.service"
}
