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

# Usage:
#   ./prepare-online.sh [x64|arm64] [22.15.0]
#
# If version is omitted, script resolves the latest v22 release.

ARCH="${1:-x64}"
VERSION="${2:-}"

case "${ARCH}" in
  x64) NODE_ARCH="x64" ;;
  arm64) NODE_ARCH="arm64" ;;
  *)
    echo "Unsupported arch: ${ARCH}. Use x64 or arm64."
    exit 1
    ;;
esac

if [[ -z "${VERSION}" ]]; then
  # Pick latest v22 from official index without triggering pipefail/SIGPIPE.
  INDEX_FILE="$(mktemp)"
  curl -fsSL "https://nodejs.org/dist/index.tab" -o "${INDEX_FILE}"
  VERSION="$(awk 'NR>1 && $1 ~ /^v22\./ {print substr($1,2); exit}' "${INDEX_FILE}")"
  rm -f "${INDEX_FILE}"
fi

if [[ -z "${VERSION}" ]]; then
  echo "Unable to resolve Node.js v22 version."
  exit 1
fi

NODE_DIR="node-v${VERSION}-linux-${NODE_ARCH}"
ARCHIVE="${NODE_DIR}.tar.xz"
BASE_URL="https://nodejs.org/dist/v${VERSION}"
OUT_DIR="bundle-node-v${VERSION}-linux-${NODE_ARCH}"

mkdir -p "${OUT_DIR}"

echo "Downloading Node.js v${VERSION} (${NODE_ARCH})..."
curl -fL "${BASE_URL}/${ARCHIVE}" -o "${OUT_DIR}/${ARCHIVE}"
curl -fL "${BASE_URL}/SHASUMS256.txt" -o "${OUT_DIR}/SHASUMS256.txt"

echo "Verifying checksum..."
(
  cd "${OUT_DIR}"
  sha256sum -c SHASUMS256.txt --ignore-missing | awk "/${ARCHIVE}: OK/"
)

cat > "${OUT_DIR}/INSTALL_ARGS.txt" <<EOF
ARCH=${NODE_ARCH}
VERSION=${VERSION}
ARCHIVE=${ARCHIVE}
EOF

echo
echo "Ready: ${OUT_DIR}"
echo "Copy this folder to the offline Ubuntu 20.04 machine."
