#!/bin/bash
set -e
PKG_DIR="$(cd "$(dirname "$0")" && pwd)"
DEST="/usr/local/bin/adom-molecule"
# Binary ships as a wiki RELEASE ASSET (not in the tarball — keeps installs
# small and follows the wiki doctrine). Version comes from the package manifest.
VER="$(grep -o '"version"[^,]*' "$PKG_DIR/package.json" | grep -o '[0-9][0-9.]*' | head -1)"
BIN_URL="https://wiki.adom.inc/download/adom/adom-molecule/${VER}/adom-molecule"
TMP_BIN="$(mktemp)"
if curl -fsSL "$BIN_URL" -o "$TMP_BIN"; then
  :
elif [ -f "$PKG_DIR/adom-molecule" ]; then
  echo "WARN: release download failed; using tarball-local binary" >&2
  cp "$PKG_DIR/adom-molecule" "$TMP_BIN"
else
  echo "ERROR: could not download adom-molecule from $BIN_URL" >&2
  exit 1
fi
if [ -w "$(dirname "$DEST")" ]; then install -m 0755 "$TMP_BIN" "$DEST"; else sudo install -m 0755 "$TMP_BIN" "$DEST"; fi
rm -f "$TMP_BIN"
echo "Installed adom-molecule ${VER} → $DEST"

# A stale copy/symlink in ~/.local/bin wins on PATH and shadows this install —
# the user then keeps running the OLD binary after every update (field report:
# adom/molecule-pipeline #190, rule 5). Clear any shadow that isn't $DEST.
SHADOW_USER="${SUDO_USER:-$(id -un)}"
SHADOW_HOME="$(getent passwd "$SHADOW_USER" | cut -d: -f6)"
for shadow in "$SHADOW_HOME/.local/bin/adom-molecule" "$HOME/.local/bin/adom-molecule"; do
  if { [ -e "$shadow" ] || [ -L "$shadow" ]; } && [ "$shadow" != "$DEST" ]; then
    echo "Removing stale shadow install: $shadow (was masking $DEST)" >&2
    rm -f "$shadow"
  fi
done

# Skills: root SKILL.md = the adom-molecule skill; sub-skills under skills/<name>/.
# Copy real files (no symlinks), clearing any prior dir or symlink from an old install.
# Under sudo, $HOME is /root — resolve the REAL user's home via SUDO_USER so the
# skills land where Claude Code (running as that user) can see them.
TARGET_USER="${SUDO_USER:-$(id -un)}"
TARGET_HOME="$(getent passwd "$TARGET_USER" | cut -d: -f6)"
SKILLS_DIR="$TARGET_HOME/.claude/skills"
mkdir -p "$SKILLS_DIR"
install_skill() { # <install-name> <source SKILL.md>
  [ -f "$2" ] || return 0
  rm -rf "$SKILLS_DIR/$1"
  mkdir -p "$SKILLS_DIR/$1"
  cp "$2" "$SKILLS_DIR/$1/SKILL.md"
  [ -n "${SUDO_USER:-}" ] && chown -R "$TARGET_USER" "$SKILLS_DIR/$1"
  echo "Installed skill → $SKILLS_DIR/$1/SKILL.md"
}
install_skill adom-molecule "$PKG_DIR/SKILL.md"
for d in "$PKG_DIR"/skills/*/; do
  [ -d "$d" ] || continue
  install_skill "$(basename "$d")" "$d/SKILL.md"
done
