#!/bin/bash
# Produce the offline npm dependency tree for the opencode packages.
#
# The CLI is built by `bun build --compile` and the desktop app by
# electron-vite; both need their dependency closures present on disk and
# neither can be built from a plain release tarball. This script runs the
# install once, drops the platforms the package does not build for, and
# leaves the result as an unpacked directory to commit. It also snapshots
# the models.dev catalogue, which the build otherwise fetches.
#
# Run on a host with bun and network access, from the package directory:
#
#     ./opencode_vendor --source opencode-<version>.tar
#
# It needs bun, tar, curl and python3. Commit the result with
#
#     git add -A -f vendor
#
# The -f is required: several vendored packages ship their own .gitignore
# files (ghostty-web ignores its dist/), and a plain git add would silently
# drop those files from the tree the package builds from.

set -euo pipefail

outdir="."
source_archive=""
version=""

while [ $# -gt 0 ]; do
    case "$1" in
        --source)  source_archive="$2"; shift 2 ;;
        --version) version="$2"; shift 2 ;;
        --outdir)  outdir="$2"; shift 2 ;;
        *) echo "$0: unknown option: $1" >&2; exit 1 ;;
    esac
done

[ -n "$source_archive" ] && [ -f "$source_archive" ] || {
    echo "$0: pass --source <opencode-<version>.tar>" >&2; exit 1
}
if [ -z "$version" ]; then
    version=$(basename "$source_archive" .tar)
    version=${version#opencode-}
fi

need() { command -v "$1" >/dev/null || { echo "$1 is required" >&2; exit 1; }; }
need bun; need tar; need curl; need python3

work="$(mktemp -d)"
trap 'rm -rf "$work"' EXIT
tar -xf "$source_archive" -C "$work"
tree="$(find "$work" -maxdepth 1 -mindepth 1 -type d | head -1)"
[ -f "$tree/package.json" ] || { echo "unexpected source layout" >&2; exit 1; }

echo "==> dropping build-only tooling we do not invoke"
# electron-builder is upstream's packaging tool; the package assembles the
# desktop app directory itself, so its dependency tree (including the
# prebuilt app-builder-bin Go binaries) never has to exist on disk.
python3 - "$tree/packages/desktop/package.json" <<'PY'
import json, sys
path = sys.argv[1]
with open(path, encoding="utf-8") as f:
    pkg = json.load(f)
pkg.get("devDependencies", {}).pop("electron-builder", None)
with open(path, "w", encoding="utf-8") as f:
    json.dump(pkg, f, indent=2)
    f.write("\n")
print("    dropped devDependencies.electron-builder from packages/desktop")
PY

echo "==> installing npm dependencies"
# --filter restricts the install to the CLI, its build script and the desktop
# app (whose renderer build pulls in the app/ui workspaces); without it bun
# resolves the whole monorepo, including the web and console trees and their
# assets. The lockfile is deliberately not frozen: bun rewrites the key order
# of trustedDependencies and patchedDependencies, so a bun newer than the one
# upstream pins always reports the lockfile as changed.
( cd "$tree" && bun install --ignore-scripts --no-progress \
      --cpu '*' --os '*' \
      --filter './packages/opencode' --filter './packages/script' \
      --filter './packages/desktop' >/dev/null )

store="$tree/node_modules/.bun"

echo "==> dropping foreign platforms"
# --cpu/--os '*' pulls the optionalDependencies of every platform. Keep linux
# x86_64 and aarch64 against glibc, which is what the package builds for.
python3 - "$store" <<'PY'
import os, re, shutil, sys
store = sys.argv[1]
foreign = re.compile(r'(darwin|win32|windows|freebsd|openbsd|sunos|netbsd|android'
                     r'|musleabihf|-musl|linux-arm-|linux-arm@|linux-ia32'
                     r'|ppc64|s390x|riscv64|loong)')
n = 0
for name in sorted(os.listdir(store)):
    if foreign.search(name):
        shutil.rmtree(os.path.join(store, name)); n += 1
print("    dropped %d entries" % n)
PY

echo "==> dropping foreign platform files inside the packages we keep"
# Several portable packages carry a prebuilt binary for every platform in one
# directory; none of the non-linux ones can run here.
python3 - "$store" <<'PY'
import os, shutil, sys
store = sys.argv[1]
foreign_dir = ('win32-', 'darwin-', 'android-', 'freebsd-', 'linux-arm-',
               'linux-ia32-', 'linux-x64-musl', 'linux-arm64-musl')
freed = 0
for root, dirs, files in os.walk(store, topdown=True):
    for d in list(dirs):
        p = os.path.join(root, d)
        drop = (os.path.basename(root) == 'prebuilds' and d.startswith(foreign_dir)) \
            or p.endswith(('clipboardy/fallbacks/windows', 'web-tree-sitter/debug'))
        if drop:
            freed += sum(os.path.getsize(os.path.join(r, f))
                         for r, _, fs in os.walk(p) for f in fs)
            shutil.rmtree(p); dirs.remove(d)
    for f in files:
        p = os.path.join(root, f)
        if f.endswith(('.dylib', '.dll', '.exe')) or f.endswith('.tgz') \
                or p.endswith('clipboardy/fallbacks/linux/xsel'):
            freed += os.path.getsize(p); os.remove(p)
print("    freed %.1f MB" % (freed / 1048576))
PY

echo "==> writing the dependency tree"
# The per-workspace node_modules are symlink farms into node_modules/.bun and
# are not reconstructible without rerunning the install, so they are kept.
rm -rf "$outdir/vendor"
mkdir -p "$outdir/vendor"
cp -a "$tree/node_modules" "$outdir/vendor/node_modules"
while read -r nm; do
    [ -n "$nm" ] || continue
    mkdir -p "$outdir/vendor/$(dirname "$nm")"
    cp -a "$tree/$nm" "$outdir/vendor/$nm"
done < <(cd "$tree" && find packages -maxdepth 3 -name node_modules -type d | sort)

echo "==> snapshotting the models.dev catalogue"
curl -fsSL -o "$outdir/models.dev-api-$version.json" https://models.dev/api.json

echo
printf '%10s  vendor/\n' "$(du -sh "$outdir/vendor" | cut -f1)"
printf '%10s  models.dev-api-%s.json\n' "$(du -h "$outdir/models.dev-api-$version.json" | cut -f1)" "$version"
