#!/bin/sh
# Installs csm, the Code Session Manager, from its GitHub releases. It needs only curl and tar: no Go, no Node.
#
#   curl -fsSL https://csm-web-ten.vercel.app/install.sh | sh
#
# CSM_VERSION=0.12.0 pins a version; CSM_INSTALL_DIR=/some/dir installs somewhere other than ~/.local/bin.
set -eu

repo="onoja123/csm"
dir="${CSM_INSTALL_DIR:-$HOME/.local/bin}"

say() { printf '%s\n' "$*"; }
fail() {
  printf 'csm install: %s\n' "$*" >&2
  exit 1
}

command -v curl >/dev/null 2>&1 || fail "curl is required"
command -v tar >/dev/null 2>&1 || fail "tar is required"

case "$(uname -s)" in
  Darwin) os=darwin ;;
  Linux) os=linux ;;
  *) fail "csm runs on macOS and Linux; $(uname -s) is not supported yet" ;;
esac

case "$(uname -m)" in
  x86_64 | amd64) arch=amd64 ;;
  arm64 | aarch64) arch=arm64 ;;
  *) fail "there is no csm build for $(uname -m) yet" ;;
esac

version="${CSM_VERSION:-}"

if [ -z "$version" ]; then
  latest=$(curl -fsSL -o /dev/null -w '%{url_effective}' "https://github.com/$repo/releases/latest") ||
    fail "could not reach GitHub"
  version="${latest##*/}"
fi

version="${version#v}"
[ -n "$version" ] && [ "$version" != "latest" ] || fail "could not find the latest release"

name="csm_${version}_${os}_${arch}"
base="https://github.com/$repo/releases/download/v$version"
tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT INT TERM

say "Downloading csm $version for $os/$arch..."
curl -fsL "$base/$name.tar.gz" -o "$tmp/$name.tar.gz" || fail "csm $version has no $name.tar.gz"
curl -fsL "$base/checksums.txt" -o "$tmp/checksums.txt" || fail "could not download checksums.txt"

expected=$(awk -v f="$name.tar.gz" '$2 == f { print $1 }' "$tmp/checksums.txt")

if command -v sha256sum >/dev/null 2>&1; then
  actual=$(sha256sum "$tmp/$name.tar.gz" | awk '{ print $1 }')
else
  actual=$(shasum -a 256 "$tmp/$name.tar.gz" | awk '{ print $1 }')
fi

[ -n "$expected" ] && [ "$expected" = "$actual" ] || fail "checksum mismatch for $name.tar.gz; nothing was installed"

tar -xzf "$tmp/$name.tar.gz" -C "$tmp"
mkdir -p "$dir"
# Copy, then rename over the old binary, so a csm that is running right now keeps its own file.
cp "$tmp/$name/csm" "$dir/.csm.new"
chmod 0755 "$dir/.csm.new"
mv -f "$dir/.csm.new" "$dir/csm"

say "Installed $("$dir/csm" version | head -n 1) to $dir/csm"

case ":$PATH:" in
  *":$dir:"*) say "Next: csm setup" ;;
  *)
    say "$dir is not on your PATH yet. Add this line to your shell profile, then run csm setup:"
    say "  export PATH=\"$dir:\$PATH\""
    ;;
esac
