#!/bin/sh
# build.sh — Assemble kit-connect SPK for Synology SRM (ipq806x)
# Compatible: RT2600ac, RT6600ax, all ipq806x SRM routers.
# Output: kit-connect-0.1-0001.spk
#
# SPK structure (outer tar, UNCOMPRESSED):
#   INFO
#   PACKAGE_ICON.PNG         (72x72)
#   PACKAGE_ICON_256.PNG     (256x256)
#   scripts/
#     postinst, start-stop-status, preinst, preuninst, postuninst
#   conf/
#     privilege, resource
#   package.tgz    (gzipped inner tar: bin/ + conf/connect.conf + wizard.sh + www/)

set -e

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

PKG_NAME="kit-connect"
VERSION="0.1-0001"
OUTPUT="${PKG_NAME}-${VERSION}.spk"
BUILD_DIR="/tmp/kit-connect-build-$$"

echo "=== Building ${PKG_NAME}-${VERSION}.spk ==="

rm -rf "$BUILD_DIR"
mkdir -p "$BUILD_DIR"

# ── 1. Create inner package.tgz ─────────────────────────────────
echo "  → Creating package.tgz"
tar -czf "$BUILD_DIR/package.tgz" \
	--format=ustar \
	bin/ \
	conf/connect.conf \
	wizard.sh \
	www/

echo "  → package.tgz contents:"
tar tzf "$BUILD_DIR/package.tgz"

# ── 2. Stage and assemble outer SPK (NO checksum — deprecated) ──
STAGE="$BUILD_DIR/stage"
mkdir -p "$STAGE"
cp INFO PACKAGE_ICON.PNG PACKAGE_ICON_256.PNG "$STAGE/"
cp -r scripts "$STAGE/"
mkdir -p "$STAGE/conf"
cp conf/privilege conf/resource "$STAGE/conf/"
cp "$BUILD_DIR/package.tgz" "$STAGE/"

echo "  → Assembling SPK"
tar -cf "${OUTPUT}" -C "$STAGE" --format=ustar \
	INFO PACKAGE_ICON.PNG PACKAGE_ICON_256.PNG scripts conf package.tgz

echo "  → Verifying SPK contents"
tar -tf "${OUTPUT}" | sort

SIZE=$(stat -f%z "${OUTPUT}" 2>/dev/null || stat -c%s "${OUTPUT}" 2>/dev/null)
echo ""
echo "=== Build complete: ${OUTPUT} ==="
echo "    Size: ${SIZE} bytes"
echo "    MD5:  $(md5sum "${OUTPUT}" | awk '{print $1}')"

rm -rf "$BUILD_DIR"
