#!/bin/sh
# build.sh — Assemble syno-balance SPK for Synology SRM (noarch)
# Output: syno-balance-0.1-0001.spk
# TEST BUILD — not for production.
# Compatible: RT2600ac, RT6600ax, all ipq806x SRM routers.

set -e

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

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

echo "=== Building ${PKG_NAME}-${VERSION}.spk (TEST BUILD) ==="

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

# Inner package.tgz
tar -czf "$BUILD_DIR/package.tgz" --format=ustar bin/ etc/

# Stage outer SPK
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/"

# Assemble (no checksum — deprecated)
tar -cf "${OUTPUT}" -C "$STAGE" --format=ustar \
	INFO PACKAGE_ICON.PNG PACKAGE_ICON_256.PNG scripts conf package.tgz

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

SIZE=$(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"
