#!/usr/bin/env bash

# omarchy:summary=Install Node.js, Bun, Deno, yarn, pnpm, Biome, oxlint, oxfmt and watchman, with a release cooldown on npm and pnpm
# omarchy:requires-sudo=true

# Based: the JavaScript toolchain the retired dev tooling installed, through
# asdf and npm. watchman comes from brew on the Mac; Debian dropped the package
# after bookworm, so that build's binary goes to /usr/local/bin with the
# inotify limits it needs. yarn2init is the Yarn Berry project starter. npm and
# pnpm refuse anything published in the last five days (BASED-91); yarn classic
# has no such setting and is covered by Install > Development > Socket Firewall.

set -eo pipefail

asdf_data=${ASDF_DATA_DIR:-$HOME/.asdf}
omarchy-pkg-add asdf
export PATH="$asdf_data/shims:$PATH"

omarchy-pkg-add curl linux=only gawk gpg linux=only dirmngr linux=only
for plugin in nodejs bun deno yarn pnpm; do
  echo -e "Installing $plugin...\n"
  omarchy-dev-env-tool "$plugin"
done

echo -e "\nInstalling Biome, oxlint and oxfmt...\n"
npm install -g @biomejs/biome oxlint oxfmt
asdf reshim nodejs

echo -e "\nInstalling watchman...\n"
if [[ $(omarchy-os) == darwin ]]; then
  omarchy-pkg-add watchman
elif ! omarchy-cmd-present watchman; then
  arch=$(dpkg --print-architecture)
  tmp=$(mktemp -d)
  trap 'rm -rf "$tmp"' EXIT
  curl -fsSL -o "$tmp/watchman.deb" "https://deb.debian.org/debian/pool/main/w/watchman/watchman_4.9.0-7+b2_${arch}.deb"
  (cd "$tmp" && ar x watchman.deb && tar -xf data.tar.xz ./usr/bin/watchman)
  sudo install -m 0755 "$tmp/usr/bin/watchman" /usr/local/bin/watchman
  printf 'fs.inotify.max_user_watches=999999\nfs.inotify.max_queued_events=999999\nfs.inotify.max_user_instances=999999\n' |
    sudo tee /etc/sysctl.d/60-watchman.conf >/dev/null
  sudo sysctl -q -p /etc/sysctl.d/60-watchman.conf
fi

echo -e "\nInstalling yarn2init...\n"
mkdir -p ~/.local/bin
curl -fsSL -o ~/.local/bin/yarn2init https://gitlab.com/bitspur/community/yarn2init/-/raw/main/yarn2init.sh
chmod +x ~/.local/bin/yarn2init

# BASED-91: npm counts the cooldown in days, pnpm in minutes. ~/.npmrc can hold
# tokens, so the key is appended, never written over.
grep -q '^min-release-age=' ~/.npmrc 2>/dev/null || echo 'min-release-age=5' >>~/.npmrc
pnpm config set --global minimumReleaseAge 7200
