#!/bin/bash
set -euo pipefail

VERSION="${VERSION:-$(git describe --tags --always --dirty 2>/dev/null || echo dev)}"
GOARCH="${GOARCH:-amd64}"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"

echo "=== Building SyncServer v${VERSION} for ${GOARCH} ==="

echo "=== Building frontend ==="
cd "$PROJECT_DIR/web"
npm ci --silent 2>/dev/null || npm install --silent
npm run build

echo "=== Copying frontend dist to Go embed dir ==="
rm -rf "$PROJECT_DIR/internal/webui/dist"
cp -R "$PROJECT_DIR/web/dist" "$PROJECT_DIR/internal/webui/dist"

echo "=== Building Go binary ==="
cd "$PROJECT_DIR"
CGO_ENABLED=0 GOOS=linux GOARCH="${GOARCH}" \
    go build -trimpath \
    -ldflags="-s -w -X main.version=${VERSION}" \
    -o "packaging/debian/usr/bin/syncserver" \
    ./cmd/server

echo "=== Binary size ==="
ls -lh "packaging/debian/usr/bin/syncserver"

echo "=== Done ==="
echo "Run: ./scripts/package-deb.sh to create the .deb package"
