#!/usr/bin/env bash
set -euo pipefail

VERSION="${VERSION:-dev}"
OUT_DIR="${OUT_DIR:-dist-release}"
SKIP_FRONTEND="${SKIP_FRONTEND:-0}"
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
OUT="$ROOT/$OUT_DIR"

if [[ "$SKIP_FRONTEND" != "1" ]]; then
  for app in admin portal setup; do
    web_dir="$ROOT/web/$app"
    if [[ ! -d "$web_dir/node_modules" ]]; then
      (cd "$web_dir" && npm install)
    fi
    (cd "$web_dir" && npm run build)
  done
fi

mkdir -p "$OUT"

copy_if_exists() {
  local source="$1"
  local target="$2"
  if [[ -e "$source" ]]; then
    rm -rf "$target"
    mkdir -p "$(dirname "$target")"
    cp -R "$source" "$target"
  fi
}

REPO_ROOT="$(cd "$ROOT/../.." && pwd)"
DATA_UPDATE_PUBLIC="$OUT/data/update/public"
DATA_UPDATE_NOTICE="$OUT/data/update-notice"
mkdir -p "$DATA_UPDATE_PUBLIC"
copy_if_exists "$REPO_ROOT/update-notice" "$DATA_UPDATE_NOTICE"
for name in update-info.json media-types.json tool-status.json modules.json; do
  if [[ -f "$REPO_ROOT/server/update/public/$name" ]]; then
    cp -f "$REPO_ROOT/server/update/public/$name" "$DATA_UPDATE_PUBLIC/$name"
  fi
done
copy_if_exists "$REPO_ROOT/server/update/public/downloads" "$DATA_UPDATE_PUBLIC/downloads"

build_target() {
  local goos="$1"
  local goarch="$2"
  local name="$3"
  (cd "$ROOT" && \
    GOOS="$goos" GOARCH="$goarch" CGO_ENABLED=0 \
    go build -tags embed_web -buildvcs=false -trimpath -ldflags "-s -w -X ymhut-box/server/unified-management/internal/config.Version=$VERSION" \
    -o "$OUT/$name" ./cmd/unified-management)
}

build_target windows amd64 ymhut-unified-management-windows-amd64.exe
build_target linux amd64 ymhut-unified-management-linux-amd64
build_target linux arm64 ymhut-unified-management-linux-arm64

echo "Built release binaries in $OUT"
