#!/bin/bash
# WHAT: Build the APSDashboard.spk Synology package file
# WHY:  A .spk is a tar archive containing INFO, lifecycle scripts, and package.tgz.
#       This script assembles those pieces from ui/spk/ and writes APSDashboard.spk.
# HOW:  Run from the APS project root:
#         bash ui/scripts/build-spk.sh
#       Or from the ui/ directory:
#         bash scripts/build-spk.sh
#       The output file is written to ui/spk/APSDashboard.spk

set -e

# Resolve the ui/ directory regardless of where the script is called from
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
UI_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
SPK_DIR="$UI_DIR/spk"
OUT="$SPK_DIR/APSDashboard.spk"

echo "[build-spk] Building from: $SPK_DIR"

# Verify required files exist
for f in INFO scripts/postinst scripts/preuninst scripts/start-stop-status conf/privilege; do
  if [ ! -f "$SPK_DIR/$f" ]; then
    echo "[build-spk] ERROR: Missing required file: spk/$f"
    exit 1
  fi
done

# Step 1: Create package.tgz from package_root/ contents
# WHY: package.tgz is extracted to /var/packages/APSDashboard/target/ on install.
#      It must contain the runtime files (nginx boot hook, DSM launcher config).
echo "[build-spk] Creating package.tgz from package_root/ ..."
cd "$SPK_DIR/package_root"
tar -czf "$SPK_DIR/package.tgz" .
cd "$SPK_DIR"

# Step 2: Assemble the .spk
# WHY: A .spk is a plain tar (NOT gzip-compressed) containing:
#       INFO, icon images, conf/, scripts/, and package.tgz
# Note: PACKAGE_ICON.PNG and PACKAGE_ICON_256.PNG are optional —
#       include them only if they exist.
echo "[build-spk] Assembling APSDashboard.spk ..."

ICON_FILES=""
[ -f "$SPK_DIR/PACKAGE_ICON.PNG" ]     && ICON_FILES="$ICON_FILES PACKAGE_ICON.PNG"
[ -f "$SPK_DIR/PACKAGE_ICON_256.PNG" ] && ICON_FILES="$ICON_FILES PACKAGE_ICON_256.PNG"

tar -cf "$OUT" \
  INFO \
  $ICON_FILES \
  conf \
  scripts \
  package.tgz

echo "[build-spk] Done: $OUT"
echo ""
echo "Install via DSM Package Manager → Manual Install → select APSDashboard.spk"
