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

# Always run from repo root
JFROG_BEARER_TOKEN=$(get_env APIC_DEV_LOCAL_TOKEN "")

# JFrog config
JFROG_URL="https://na.artifactory.swg-devops.com/artifactory"
REPO="apic-dev-generic-local"
BASE_PATH="velox/apic-cli"
AUTH_HEADER="Authorization: Bearer $JFROG_BEARER_TOKEN"

# Query Artifactory for existing versions
RAW_CHILDREN=$(curl -s -H "$AUTH_HEADER" \
  "$JFROG_URL/api/storage/$REPO/$BASE_PATH" | jq -r '.children[].uri')

# Extract only semantic version folders
LATEST_VERSION=$(echo "$RAW_CHILDREN" \
  | grep -Eo '[0-9]+\.[0-9]+\.[0-9]+(-[0-9]+)?' \
  | sort -V | tail -1 || true)

if [[ -z "$LATEST_VERSION" ]]; then
  echo "No existing versions found under $BASE_PATH"
  NEXT_VERSION="12.0.0-1"
else
  BASE=$(echo "$LATEST_VERSION" | cut -d- -f1)
  REV=$(echo "$LATEST_VERSION" | grep -oE '[0-9]+$' || echo 0)
  NEXT_VERSION="$BASE-$((REV+1))"
fi

echo "Publishing new version: $NEXT_VERSION"

npm install
npm i -g @yao-pkg/pkg
npm run build || { echo "TypeScript compilation failed"; exit 1; }

pwd 


# Build executables using pkg
mkdir -p release/$NEXT_VERSION/amd64/{linux,osx,windows}



# Linux
pkg dist/cli.cjs --targets node20-linux-x64 --output release/$NEXT_VERSION/amd64/linux/apic
# macOS
pkg dist/cli.cjs --targets node20-macos-x64 --output release/$NEXT_VERSION/amd64/osx/apic
# Windows
pkg dist/cli.cjs --targets node20-win-x64 --output release/$NEXT_VERSION/amd64/windows/apic.exe

# Upload to JFrog
for platform in linux osx windows; do
  FILE="release/$NEXT_VERSION/amd64/$platform/$( [[ $platform == windows ]] && echo apic.exe || echo apic )"
  TARGET="$JFROG_URL/$REPO/$BASE_PATH/$NEXT_VERSION/amd64/$platform/$(basename $FILE)"
  echo "Uploading $FILE → $TARGET"
  curl -H "$AUTH_HEADER" -T "$FILE" "$TARGET"
done

echo "All binaries uploaded successfully."
