#!/bin/sh
# Installs or updates beckon for the current user. No sudo, no package manager.
#
#   curl -fsSL https://beckon.openyard.cloud/install.sh | sh
#
# What it does:
#   - unpacks beckon's source from GitHub into ~/.beckon/app (beckon has no dependencies)
#   - uses your Node.js when it is 22 or newer, or else downloads the official Node.js 22
#     build into ~/.beckon/node and checks it against nodejs.org's SHASUMS256.txt
#   - writes the `beckon` command to ~/.local/bin
#   - a first install then starts `beckon init`; an update restarts beckon's service
# It never touches your config, tokens or state in ~/.beckon, and never edits a shell profile.
#
# Settings (environment variables):
#   BECKON_REF          branch or tag to install (default: main)
#   BECKON_HOME         beckon's folder, as beckon itself reads it (default: ~/.beckon)
#   BECKON_INSTALL_DIR  where app/ and node/ go (default: BECKON_HOME)
#   BECKON_BIN_DIR      where the `beckon` command goes (default: ~/.local/bin)
#   BECKON_NO_INIT=1    do not start `beckon init` at the end
set -eu

REPO="openyard-cloud/beckon"
NODE_MAJOR=22
ref="${BECKON_REF:-main}"
home="${BECKON_HOME:-$HOME/.beckon}"
root="${BECKON_INSTALL_DIR:-$home}"
bin_dir="${BECKON_BIN_DIR:-$HOME/.local/bin}"
tarball="${BECKON_TARBALL:-https://github.com/$REPO/archive/$ref.tar.gz}"

say() { printf '%s\n' "$*"; }
fail() { printf 'beckon install: %s\n' "$*" >&2; exit 1; }
have() { command -v "$1" >/dev/null 2>&1; }

# download <url> <file>
download() {
  if have curl; then
    curl -fsSL --retry 2 -o "$2" "$1"
  elif have wget; then
    wget -q -O "$2" "$1"
  else
    fail "curl or wget is needed to download files."
  fi
}

sha256_of() {
  if have sha256sum; then
    sha256sum "$1" | cut -d ' ' -f 1
  elif have shasum; then
    shasum -a 256 "$1" | cut -d ' ' -f 1
  else
    fail "sha256sum or shasum is needed to check the Node.js download."
  fi
}

# Prints the major version of a node binary, or nothing when it does not run.
node_major() {
  "$1" -p 'process.versions.node.split(".")[0]' 2>/dev/null || true
}

good_node() {
  major="$(node_major "$1")"
  case "$major" in '' | *[!0-9]*) return 1 ;; esac
  [ "$major" -ge "$NODE_MAJOR" ]
}

# Everything runs from one function, called on the last line: if the download of this script is
# cut short, the shell reads an unfinished function and runs nothing.
main() {

case "$(uname -s)" in
  Darwin) os=darwin ;;
  Linux) os=linux ;;
  *) fail "beckon runs on macOS and Linux, not $(uname -s)." ;;
esac
case "$(uname -m)" in
  arm64 | aarch64) arch=arm64 ;;
  x86_64 | amd64) arch=x64 ;;
  *) fail "beckon's installer knows arm64 and x64 machines, not $(uname -m)." ;;
esac

# ---- git ----

if [ "$os" = darwin ]; then
  # /usr/bin/git exists on every Mac, but only works once the command line tools are installed.
  if ! xcode-select -p >/dev/null 2>&1 && ! { have git && [ "$(command -v git)" != /usr/bin/git ]; }; then
    fail "git is missing. Install Apple's command line tools with: xcode-select --install   Then run this again."
  fi
elif ! have git; then
  if have apt-get; then hint="sudo apt-get install -y git"
  elif have dnf; then hint="sudo dnf install -y git"
  elif have pacman; then hint="sudo pacman -S git"
  elif have apk; then hint="sudo apk add git"
  else hint="install git with your system's package manager"
  fi
  fail "git is missing. Install it with: $hint   Then run this again."
fi
have tar || fail "tar is missing. Install it, then run this again."

mkdir -p "$root" "$bin_dir"
chmod 700 "$root" 2>/dev/null || true
tmp="$(mktemp -d "$root/.install.XXXXXX")"
trap 'rm -rf "$tmp"' EXIT
trap 'exit 130' INT TERM

# ---- Node.js ----

node=""
if have node && good_node "$(command -v node)"; then
  node="$(command -v node)"
  say "Node.js: using $node (v$("$node" -p process.versions.node))"
elif [ -x "$root/node/bin/node" ] && good_node "$root/node/bin/node"; then
  node="$root/node/bin/node"
  say "Node.js: using beckon's own copy (v$("$node" -p process.versions.node))"
else
  if [ "$os" = linux ] && { [ -e /lib/ld-musl-x86_64.so.1 ] || [ -e /lib/ld-musl-aarch64.so.1 ]; }; then
    fail "Node.js $NODE_MAJOR or newer is needed, and nodejs.org has no build for this system (musl). Install it with: sudo apk add nodejs   Then run this again."
  fi
  say "Node.js: $NODE_MAJOR or newer not found, downloading the official build into $root/node"
  dist="https://nodejs.org/dist/latest-v$NODE_MAJOR.x"
  download "$dist/SHASUMS256.txt" "$tmp/SHASUMS256.txt"
  line="$(grep " node-v[0-9.]*-$os-$arch\.tar\.gz\$" "$tmp/SHASUMS256.txt" | head -n 1)"
  [ -n "$line" ] || fail "nodejs.org lists no Node.js $NODE_MAJOR build for $os-$arch."
  want="${line%% *}"
  file="${line##* }"
  download "$dist/$file" "$tmp/$file"
  got="$(sha256_of "$tmp/$file")"
  [ "$got" = "$want" ] || fail "the Node.js download does not match nodejs.org's checksum. Nothing was installed."
  mkdir "$tmp/node"
  tar -xzf "$tmp/$file" -C "$tmp/node" --strip-components 1
  good_node "$tmp/node/bin/node" || fail "the downloaded Node.js does not run on this machine."
  rm -rf "$root/node.old"
  [ -d "$root/node" ] && mv "$root/node" "$root/node.old"
  mv "$tmp/node" "$root/node"
  rm -rf "$root/node.old"
  node="$root/node/bin/node"
  say "Node.js: installed v$("$node" -p process.versions.node) (checksum verified)"
fi

# ---- beckon ----

updating=""
[ -f "$root/app/bin/beckon.mjs" ] && updating=1
say "beckon: downloading $ref from github.com/$REPO"
download "$tarball" "$tmp/beckon.tar.gz" || fail "could not download $tarball"
mkdir "$tmp/app"
tar -xzf "$tmp/beckon.tar.gz" -C "$tmp/app" --strip-components 1
[ -f "$tmp/app/bin/beckon.mjs" ] && [ -f "$tmp/app/package.json" ] || fail "the download is not beckon's source. Nothing was changed."
version="$("$node" "$tmp/app/bin/beckon.mjs" --version 2>/dev/null)" || fail "the downloaded beckon does not start with $node. Nothing was changed."

# Swap the new copy in with two renames, so there is never a half-written app folder.
rm -rf "$root/app.old"
[ -d "$root/app" ] && mv "$root/app" "$root/app.old"
mv "$tmp/app" "$root/app"
rm -rf "$root/app.old"

launcher="$bin_dir/beckon"
cat > "$tmp/launcher" <<EOF
#!/bin/sh
# The beckon command, written by beckon's install.sh. Run that again to update.
node="$node"
[ -x "\$node" ] || node="\$(command -v node || true)"
if [ -z "\$node" ]; then
  echo "beckon: Node.js was not found. Run the install command again: curl -fsSL https://beckon.openyard.cloud/install.sh | sh" >&2
  exit 1
fi
exec "\$node" "$root/app/bin/beckon.mjs" "\$@"
EOF
chmod 755 "$tmp/launcher"
mv "$tmp/launcher" "$launcher"
if [ -n "$updating" ]; then say "beckon: updated to $version in $root/app"; else say "beckon: installed $version in $root/app"; fi
say "beckon: the command is $launcher"

# ---- what is left for the person to do ----

case ":$PATH:" in
  *":$bin_dir:"*) ;;
  *)
    case "$bin_dir" in
      "$HOME"/*) shown="\$HOME${bin_dir#"$HOME"}" ;;
      *) shown="$bin_dir" ;;
    esac
    case "${SHELL:-}" in
      */zsh) add="echo 'export PATH=\"$shown:\$PATH\"' >> ~/.zshrc" ;;
      */fish) add="fish_add_path $bin_dir" ;;
      */bash) if [ "$os" = darwin ]; then add="echo 'export PATH=\"$shown:\$PATH\"' >> ~/.bash_profile"; else add="echo 'export PATH=\"$shown:\$PATH\"' >> ~/.bashrc"; fi ;;
      *) add="export PATH=\"$shown:\$PATH\"   (add this line to your shell's profile)" ;;
    esac
    say "PATH: $bin_dir is not on your PATH. Add it, then open a new terminal:"
    say "  $add"
    ;;
esac

other="$(command -v beckon 2>/dev/null || true)"
if [ -n "$other" ] && [ "$other" != "$launcher" ]; then
  say "Note: another beckon comes first on your PATH: $other"
  say "  Remove it (for an npm install: npm uninstall -g beckon), or call this one as $launcher"
fi

if ! have claude; then
  say "Claude Code: not found. beckon runs it, so install it and log in before \"beckon init\":"
  say "  curl -fsSL https://claude.ai/install.sh | bash"
  say "  claude"
fi

if [ "$os" = darwin ]; then
  service_file="$HOME/Library/LaunchAgents/cloud.openyard.beckon.plist"
else
  service_file="$HOME/.config/systemd/user/beckon.service"
fi

if [ -f "$service_file" ] && grep -qF "$root/app/bin/beckon.mjs" "$service_file" 2>/dev/null; then
  say "Service: restarting beckon. Tasks that are running finish first."
  "$launcher" service restart || say "Service: the restart failed. Run: beckon service restart"
elif [ -f "$service_file" ]; then
  say "Service: a beckon service from another install is running, and it was left alone."
  say "  To run this install in the background instead: beckon service install"
elif [ -f "$home/config.json" ]; then
  say "Done. beckon is already set up in $home. Start it with: beckon start   (or: beckon service install)"
elif [ -n "${BECKON_NO_INIT:-}" ] || ! have claude; then
  say "Done. Next, run: beckon init"
elif [ -t 1 ] && (: < /dev/tty) 2>/dev/null; then
  say "Done. Starting the guided setup (beckon init)."
  "$launcher" init < /dev/tty
else
  say "Done. Next, run: beckon init"
fi

}

main "$@"
