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

# Fetches the official mycelium release binary and places it in src-tauri/binaries/
# with the target-triple suffix expected by Tauri's externalBin bundler.
#
# Usage: scripts/fetch-mycelium.sh [VERSION]
#   VERSION defaults to MYCELIUM_VERSION below.

MYCELIUM_VERSION="${1:-${MYCELIUM_VERSION:-v0.6.1}}"
REPO="threefoldtech/mycelium"

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
DEST_DIR="${ROOT_DIR}/src-tauri/binaries"
mkdir -p "${DEST_DIR}"

detect_target_triple() {
  local arch os
  arch="$(uname -m)"
  os="$(uname -s | tr '[:upper:]' '[:lower:]')"
  case "${os}-${arch}" in
    linux-x86_64) echo "x86_64-unknown-linux-gnu" ;;
    linux-aarch64) echo "aarch64-unknown-linux-gnu" ;;
    *) echo "unsupported: ${os}-${arch}" >&2; exit 1 ;;
  esac
}

# Map our target triple to the asset name pattern used by upstream releases.
asset_for_triple() {
  case "$1" in
    x86_64-unknown-linux-gnu) echo "mycelium-x86_64-unknown-linux-musl.tar.gz" ;;
    aarch64-unknown-linux-gnu) echo "mycelium-aarch64-unknown-linux-musl.tar.gz" ;;
    *) echo "unsupported triple: $1" >&2; exit 1 ;;
  esac
}

TRIPLE="$(detect_target_triple)"
ASSET="$(asset_for_triple "${TRIPLE}")"
URL="https://github.com/${REPO}/releases/download/${MYCELIUM_VERSION}/${ASSET}"

TMP_DIR="$(mktemp -d)"
trap 'rm -rf "${TMP_DIR}"' EXIT

echo "→ downloading ${URL}"
curl -fsSL "${URL}" -o "${TMP_DIR}/mycelium.tar.gz"

echo "→ extracting"
tar -xzf "${TMP_DIR}/mycelium.tar.gz" -C "${TMP_DIR}"

# The archive contains a single 'mycelium' binary at the root.
SRC="${TMP_DIR}/mycelium"
if [[ ! -f "${SRC}" ]]; then
  # Some releases nest the binary; find it.
  SRC="$(find "${TMP_DIR}" -name 'mycelium' -type f -executable | head -n1)"
fi
if [[ -z "${SRC}" || ! -f "${SRC}" ]]; then
  echo "could not locate mycelium binary in archive" >&2
  exit 1
fi

DEST="${DEST_DIR}/mycelium-${TRIPLE}"
install -m 0755 "${SRC}" "${DEST}"
echo "✓ installed ${DEST}"
echo "  version: ${MYCELIUM_VERSION}"
echo "  size:    $(stat -c%s "${DEST}") bytes"
