#!/bin/sh
# Hodos installer for macOS and Linux.
#   curl -fsSL https://usehodos.com/install.sh | sh
#   curl -fsSL https://usehodos.com/install.sh | sh -s -- <extra init args>
# Uses node >= 22.13 from PATH, or downloads Node 22 LTS into ~/.hodos/node (sha256 checked).
# Then runs `hodos-cli init` and adds a `hodos` command in ~/.hodos/bin.
# HODOS_NO_INIT=1 skips the init step.
set -eu

HODOS="$HOME/.hodos"
DIST="https://nodejs.org/dist/latest-v22.x"

say() { printf 'hodos: %s\n' "$*"; }
die() { printf 'hodos: error: %s\n' "$*" >&2; exit 1; }
need() { command -v "$1" >/dev/null 2>&1 || die "'$1' is required but was not found. Install it and run this again."; }

# True if the given node binary is >= 22.13.
node_ok() {
  "$1" -e 'const [a,b]=process.versions.node.split(".").map(Number);process.exit(a>22||(a===22&&b>=13)?0:1)' >/dev/null 2>&1
}

sha256() {
  if command -v sha256sum >/dev/null 2>&1; then sha256sum "$1" | cut -d' ' -f1
  else shasum -a 256 "$1" | cut -d' ' -f1
  fi
}

install_node() {
  need curl
  need tar
  command -v sha256sum >/dev/null 2>&1 || command -v shasum >/dev/null 2>&1 || die "'sha256sum' or 'shasum' is required to verify the download."
  case "$(uname -s)" in
    Darwin) os=darwin ;;
    Linux) os=linux ;;
    *) die "unsupported OS '$(uname -s)'. Hodos supports macOS, Linux and Windows." ;;
  esac
  case "$(uname -m)" in
    x86_64 | amd64) arch=x64 ;;
    arm64 | aarch64) arch=arm64 ;;
    *) die "unsupported CPU '$(uname -m)'. Hodos supports x64 and arm64." ;;
  esac
  # An x64 shell under Rosetta on Apple silicon still gets the native build.
  if [ "$os" = darwin ] && [ "$arch" = x64 ] && [ "$(sysctl -n sysctl.proc_translated 2>/dev/null || echo 0)" = 1 ]; then
    arch=arm64
  fi

  tmp=$(mktemp -d)
  trap 'rm -rf "$tmp"' EXIT

  curl -fsSL --proto '=https' "$DIST/SHASUMS256.txt" -o "$tmp/SHASUMS256.txt" || die "could not reach nodejs.org."
  line=$(grep -E " node-v22\.[0-9]+\.[0-9]+-$os-$arch\.tar\.gz\$" "$tmp/SHASUMS256.txt" | head -n 1)
  [ -n "$line" ] || die "no Node.js 22 build found for $os-$arch."
  want=${line%% *}
  file=${line##* }
  ver=${file#node-}
  ver=${ver%%-*}
  if [ -x "$HODOS/node/bin/node" ] && [ "$("$HODOS/node/bin/node" --version 2>/dev/null)" = "$ver" ]; then
    say "Node.js $ver in $HODOS/node is up to date."
    return 0
  fi
  say "Downloading Node.js $ver for $os-$arch..."
  curl -fsSL --proto '=https' "$DIST/$file" -o "$tmp/$file" || die "download of $file failed."
  [ "$(sha256 "$tmp/$file")" = "$want" ] || die "checksum mismatch for $file. Nothing was installed; try again."

  tar -xzf "$tmp/$file" -C "$tmp" || die "could not extract $file."
  mkdir -p "$HODOS"
  rm -rf "$HODOS/node"
  mv "$tmp/${file%.tar.gz}" "$HODOS/node"
  say "Installed ${file%.tar.gz} to $HODOS/node"
}

# 1. Node
if command -v node >/dev/null 2>&1 && command -v npx >/dev/null 2>&1 && node_ok node; then
  NODE=$(command -v node) # the PATH entry (e.g. Homebrew's bin link) survives upgrades; process.execPath may not
  NPX=npx
  say "Using Node.js $(node --version) at $NODE"
else
  install_node
  NODE="$HODOS/node/bin/node"
  NPX="$HODOS/node/bin/npx"
  # npm runs the CLI through `#!/usr/bin/env node`, so our node must come first on PATH.
  PATH="$HODOS/node/bin:$PATH"
  export PATH
fi

# 2. Connect this device (opens a browser and waits, so it needs the terminal, not the piped script).
if [ "${HODOS_NO_INIT:-}" = 1 ]; then
  say "HODOS_NO_INIT=1: skipping init."
else
  if ! (exec </dev/tty) 2>/dev/null; then
    die "no terminal to run init in. Run this yourself: PATH=\"$(dirname "$NODE"):\$PATH\" $NPX -y hodos-cli@latest init"
  fi
  NPM_CONFIG_UPDATE_NOTIFIER=false "$NPX" -y hodos-cli@latest init "$@" </dev/tty || die "init did not finish. Run the installer again to retry."
fi

# 3. `hodos` command
mkdir -p "$HODOS/bin"
cat >"$HODOS/bin/hodos" <<EOF
#!/bin/sh
exec "$NODE" "\$HOME/.hodos/app/dist/cli.js" "\$@"
EOF
chmod +x "$HODOS/bin/hodos"

LINE='export PATH="$HOME/.hodos/bin:$PATH" # added by hodos'
added=""
for rc in .zshrc .bashrc; do
  shell_name=${rc#.}
  shell_name=${shell_name%rc}
  # Touch the rc of the user's login shell even if it does not exist yet; otherwise only rc files that exist.
  if [ -f "$HOME/$rc" ] || [ "$(basename "${SHELL:-}")" = "$shell_name" ]; then
    if ! grep -qs '\.hodos/bin' "$HOME/$rc"; then
      printf '\n%s\n' "$LINE" >>"$HOME/$rc"
      added="$added ~/$rc"
    fi
  fi
done

if [ -n "$added" ]; then
  say "Added ~/.hodos/bin to PATH in$added. Open a new terminal to use 'hodos'."
elif ! grep -qs '\.hodos/bin' "$HOME/.zshrc" "$HOME/.bashrc"; then
  say "Add $HODOS/bin to your PATH to use 'hodos'."
fi
say "Done. Run 'hodos' for commands (or $HODOS/bin/hodos)."
