#!/bin/bash
set -e

cd "$(dirname "$0")"

# Load .env if present
if [ -f .env ]; then
  set -a; source .env; set +a
fi

# Ensure tools are on PATH
export PATH="$HOME/.npm-global/bin:$HOME/.bun/bin:$HOME/.local/bin:$PATH"

echo "=== mcpctl CLI build & release ==="
echo ""

# 1. Build TypeScript
echo "==> Building TypeScript..."
pnpm build

# 2. Bundle standalone binary
echo "==> Bundling standalone binary..."
mkdir -p dist
rm -f dist/mcpctl dist/mcpctl-*.rpm
bun build src/cli/src/index.ts --compile --outfile dist/mcpctl
echo "    Binary: $(du -h dist/mcpctl | cut -f1)"

# 3. Package RPM
echo "==> Packaging RPM..."
nfpm pkg --packager rpm --target dist/
RPM_FILE=$(ls dist/mcpctl-*.rpm 2>/dev/null | head -1)
RPM_VERSION=$(rpm -qp --queryformat '%{VERSION}-%{RELEASE}' "$RPM_FILE")
echo "    RPM: $RPM_FILE ($(du -h "$RPM_FILE" | cut -f1))"

# 4. Publish to Gitea
GITEA_URL="${GITEA_URL:-http://10.0.0.194:3012}"
GITEA_OWNER="${GITEA_OWNER:-michal}"

if [ -z "$GITEA_TOKEN" ]; then
  echo ""
  echo "WARNING: GITEA_TOKEN not set, skipping publish. Add it to .env"
  echo ""
else
  echo "==> Publishing to ${GITEA_URL}..."
  EXISTING=$(curl -s -o /dev/null -w "%{http_code}" \
    -H "Authorization: token ${GITEA_TOKEN}" \
    "${GITEA_URL}/api/v1/packages/${GITEA_OWNER}/rpm/mcpctl/${RPM_VERSION}")

  if [ "$EXISTING" = "200" ]; then
    echo "    Replacing existing version $RPM_VERSION..."
    curl -s -o /dev/null -X DELETE \
      -H "Authorization: token ${GITEA_TOKEN}" \
      "${GITEA_URL}/api/v1/packages/${GITEA_OWNER}/rpm/mcpctl/${RPM_VERSION}"
  fi

  curl --fail -s -X PUT \
    -H "Authorization: token ${GITEA_TOKEN}" \
    --upload-file "$RPM_FILE" \
    "${GITEA_URL}/api/packages/${GITEA_OWNER}/rpm/upload"
  echo "    Published!"
fi

# 5. Install locally
echo "==> Installing..."
sudo rpm -U --force "$RPM_FILE"

echo ""
echo "=== Done ==="
mcpctl --version
