#!/bin/sh
# Installs `fetch` (the Fetch Agent and CLI) on macOS or Linux:
#   curl -fsSL https://fetch.nightroll.app/install.sh | sh
# It downloads the build for this computer from https://fetch.nightroll.app/download/, checks its SHA-256 against the
# release's SHA256SUMS, and installs it into ~/.local/bin (or $FETCH_INSTALL_DIR). Rerun it to update.
set -eu

base="${FETCH_DOWNLOAD:-https://fetch.nightroll.app/download}"
dest="${FETCH_INSTALL_DIR:-$HOME/.local/bin}"

case "$(uname -s)" in
  Darwin) case $(uname -m) in arm64) target=macos-arm64 ;; *) target=macos-x86_64 ;; esac ;;
  Linux)
    case "$(uname -m)" in
      x86_64 | amd64) target=linux-x86_64 ;;
      aarch64 | arm64) target=linux-arm64 ;;
      *) echo "fetch: no build for Linux on $(uname -m) yet." >&2; exit 1 ;;
    esac ;;
  *) echo "fetch: on Windows, run in PowerShell: irm https://fetch.nightroll.app/install.ps1 | iex" >&2; exit 1 ;;
esac

sums=$(curl -fsSL "$base/SHA256SUMS")
line=$(printf '%s\n' "$sums" | grep -- "-$target\.tar\.gz\$" | head -n 1) || true
[ -n "$line" ] || { echo "fetch: the current release has no $target build." >&2; exit 1; }
sha=${line%% *}
file=${line##* }

tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT
echo "Downloading $file"
curl -fSL --progress-bar "$base/$file" -o "$tmp/$file"
if command -v shasum >/dev/null 2>&1; then got=$(shasum -a 256 "$tmp/$file"); else got=$(sha256sum "$tmp/$file"); fi
got=${got%% *}
[ "$got" = "$sha" ] || { echo "fetch: checksum mismatch for $file (expected $sha, got $got). Nothing was installed." >&2; exit 1; }

tar -xzf "$tmp/$file" -C "$tmp"
mkdir -p "$dest"
mv -f "$tmp/fetch" "$dest/fetch.new"
chmod 755 "$dest/fetch.new"
mv -f "$dest/fetch.new" "$dest/fetch"
echo "Installed $("$dest/fetch" --version) at $dest/fetch"

case ":$PATH:" in
  *":$dest:"*) ;;
  *) echo
     echo "$dest isn't on your PATH yet. Add it, e.g.:"
     echo "  echo 'export PATH=\"$dest:\$PATH\"' >> ~/.zshrc   # or ~/.bashrc" ;;
esac
echo
echo "Next: fetch login, then fetch agent install and fetch agent pair. See https://fetch.nightroll.app/download/"
