#!/bin/bash
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
ROOT="$(dirname "$SCRIPT_DIR")"

# ---------------------------------------------------------------
# 1. 检查二进制
# ---------------------------------------------------------------
BIN="$ROOT/src-tauri/target/release/bookmgr-client"
if [[ ! -f "$BIN" ]]; then
  echo "错误：未找到 $BIN，请先运行 pnpm tauri build"
  exit 1
fi

# ---------------------------------------------------------------
# 2. 读取版本号
# ---------------------------------------------------------------
VERSION=$(jq -r '.version' "$ROOT/src-tauri/tauri.conf.json")
PKG="bookmgr-client"
PKGVER="${VERSION}-1"
ARCH="x86_64"
OUTPUT="${PKG}-${PKGVER}-${ARCH}.pkg.tar.zst"

DESKTOP_FILE="$ROOT/src-tauri/target/release/bundle/deb/${PKG}_${VERSION}_amd64/data/usr/share/applications/${PKG}.desktop"
ICON_FILE="$ROOT/src-tauri/icons/128x128.png"

echo "==> 打包 ${PKG} ${PKGVER} (${ARCH})"

# ---------------------------------------------------------------
# 3. 构建 PKGBUILD + 安装目录
# ---------------------------------------------------------------
BUILD_DIR=$(mktemp -d)
trap 'rm -rf "$BUILD_DIR"' EXIT

SRCDIR="$BUILD_DIR/src"
mkdir -p "$SRCDIR/usr/bin"
mkdir -p "$SRCDIR/usr/share/applications"
mkdir -p "$SRCDIR/usr/share/icons/hicolor/128x128/apps"

install -Dm755 "$BIN" "$SRCDIR/usr/bin/${PKG}"
install -Dm644 "$DESKTOP_FILE" "$SRCDIR/usr/share/applications/${PKG}.desktop"
install -Dm644 "$ICON_FILE" "$SRCDIR/usr/share/icons/hicolor/128x128/apps/${PKG}.png"

sed -i 's/^Categories=$/Categories=Utility;/' "$SRCDIR/usr/share/applications/${PKG}.desktop"

cat > "$BUILD_DIR/PKGBUILD" << PKGEOF
pkgname=${PKG}
pkgver=${VERSION}
pkgrel=1
pkgdesc="图书管理系统桌面客户端"
arch=(x86_64)
url="https://git.msksbr.com/msksbr/bookMgr-client"
license=(MIT)
depends=(gtk3 webkit2gtk-4.1 libappindicator-gtk3)
package() {
  cp -r "\$srcdir/"* "\$pkgdir/"
}
PKGEOF

# ---------------------------------------------------------------
# 4. 用 makepkg 生成 .pkg.tar.zst
# ---------------------------------------------------------------
BUNDLE_DIR="$ROOT/src-tauri/target/release/bundle/pacman"
rm -rf "$BUNDLE_DIR"
mkdir -p "$BUNDLE_DIR"

cd "$BUILD_DIR"
makepkg -R

echo ""
echo "==> 输出: $(ls ./*.pkg.tar.zst)"
cp ./*.pkg.tar.zst "$BUNDLE_DIR/"
echo "==> 已复制到 $BUNDLE_DIR"
