#!/usr/bin/env bash
# Build dist/agent-linux/ — Linux counterpart to dist/agent/ (SirayaPrinter.exe).
set -euo pipefail

VERSION="${1:-3.0.0}"
ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
AGENT_DIR="$ROOT/dist/agent-linux"
RELEASE_DIR="$ROOT/dist/release"
DESKTOP_OUT="$ROOT/dist/desktop"

echo "=== Siraya Printer Linux agent v$VERSION ==="

cd "$ROOT"
if [[ ! -d node_modules ]]; then
  npm install
fi

echo "=== Step 1: Service release payload (linux-x64) ==="
bash installer/linux/build-release.sh "$VERSION"

echo "=== Step 2: Stage service bundle for Electron ==="
BUNDLE_STAGING="$ROOT/dist/electron-service-bundle"
rm -rf "$BUNDLE_STAGING"
mkdir -p "$BUNDLE_STAGING/payload"
cp -a "$RELEASE_DIR/payload/linux-x64" "$BUNDLE_STAGING/payload/"
cp "$ROOT/installer/linux/install-from-folder.sh" "$BUNDLE_STAGING/"
chmod +x "$BUNDLE_STAGING/install-from-folder.sh"

echo "=== Step 3: Electron desktop app (AppImage) ==="
pushd "$ROOT/desktop" >/dev/null
if [[ ! -d node_modules ]]; then
  npm install
fi
npm run build:linux
popd >/dev/null

echo "=== Step 4: Assemble dist/agent-linux/ ==="
rm -rf "$AGENT_DIR"
mkdir -p "$AGENT_DIR/service/payload"

cp -a "$RELEASE_DIR/payload/linux-x64" "$AGENT_DIR/service/payload/"
cp "$ROOT/installer/linux/install-from-folder.sh" "$AGENT_DIR/"
cp "$ROOT/installer/linux/agent-linux-Install.sh" "$AGENT_DIR/Install.sh"
cp "$ROOT/installer/linux/create-desktop-shortcut.sh" "$AGENT_DIR/"
cp "$ROOT/installer/linux/START_HERE.txt" "$AGENT_DIR/"
chmod +x "$AGENT_DIR/Install.sh" "$AGENT_DIR/install-from-folder.sh" "$AGENT_DIR/create-desktop-shortcut.sh"

APPIMG="$(find "$DESKTOP_OUT" -maxdepth 1 -name 'SirayaPrinter*.AppImage' -type f 2>/dev/null | head -1)"
if [[ -z "$APPIMG" ]]; then
  echo "ERROR: AppImage not found under $DESKTOP_OUT — electron-builder may have failed"
  exit 1
fi
cp "$APPIMG" "$AGENT_DIR/"
chmod +x "$AGENT_DIR/"*.AppImage

cat >"$AGENT_DIR/manifest.json" <<EOF
{
  "version": "$VERSION",
  "platform": "linux-x64",
  "builtAt": "$(date -u +%Y-%m-%dT%H:%M:%SZ)",
  "entry": "$(basename "$APPIMG")",
  "install": "Install.sh",
  "service": "service/payload/linux-x64",
  "uiUrl": "http://127.0.0.1:5000",
  "systemdUnit": "siraya-printer"
}
EOF

echo ""
echo "Agent folder ready at $AGENT_DIR"
echo "  Copy dist/agent-linux/ to register PC"
echo "  Run: chmod +x Install.sh && ./Install.sh"
echo "  Daily use: $(basename "$APPIMG")"
