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

# Config
USER="zunit-zsh"
PROJECT="zunit"
PACKAGE="zsh-zunit"
REQUIRES="zsh"
ARCH=$(dpkg --print-architecture)
if [[ ${ARCH} == "armhf" ]]; then ARCH="arm-v7"; fi

# Get latest version from GitHub API (returns "v0.8.2" with quotes)
VERSION_JSON=$(curl -s "https://api.github.com/repos/${USER}/${PROJECT}/tags?per_page=1")
VERSION=$(echo "${VERSION_JSON}" | jq -r '.[0].name // "v0.8.2"') # fallback
DEB_VERSION=${VERSION#v}                                          # → 0.8.2

RELEASE="1" # ← you need to define this (debian revision)
LATEST_URL="https://github.com/${USER}/${PROJECT}"

BUILD_DIR="/var/tmp/build_zunit"
mkdir -p "${BUILD_DIR}"
cd "${BUILD_DIR}"

# Optional: better maintainer info
export DEBFULLNAME="Your Name"
export DEBEMAIL="your@email.example"

# Create description-pak
cat >description-pak <<'EOF'
ZUnit is a powerful unit testing framework for ZSH.
EOF

# Minimal install script (what checkinstall will run as "make install")
cat >install.sh <<'EOF'
#!/usr/bin/env bash
set -e

INSTALL_DIR="/usr/local/bin"
ZSH_COMP_DIR="/usr/share/zsh/vendor-completions"

# Install revolver dependency
curl -L -o "${INSTALL_DIR}/revolver" \
  https://raw.githubusercontent.com/molovo/revolver/master/revolver
chmod +x "${INSTALL_DIR}/revolver"

# Clone & build ZUnit
git clone --depth 1 https://github.com/zunit-zsh/zunit.git src
cd src
./build.zsh

# Install binary
install -m 755 zunit "${INSTALL_DIR}/zunit"

# Install completion (if exists)
if [[ -f zunit.zsh-completion ]]; then
  install -D -m 644 zunit.zsh-completion "${ZSH_COMP_DIR}/_zunit"
fi
EOF

chmod +x install.sh

# Run checkinstall
checkinstall -y --fstrans=no \
  --pkgname="${PACKAGE}" \
  --pkgversion="${DEB_VERSION}" \
  --pkgrelease="${RELEASE}" \
  --pkgarch="${ARCH}" \
  --pkggroup="shells" \
  --pkglicense="MIT" \
  --pkgsource="${LATEST_URL}" \
  --maintainer="you@example.com" \
  --requires="${REQUIRES}" \
  --deldoc=yes --deldesc=yes --backup=no \
  --install=no \
  bash ./install.sh

echo "Checkinstall .deb should be in current directory."
ls -l *.deb
