#!/bin/sh
# Install the pinned sesh release without sudo or shell-profile changes.
sesh_install() {
  set -eu
  for sesh_command in node npm gh; do
    command -v "$sesh_command" >/dev/null 2>&1 || {
      printf 'sesh: %s is required. Install Node.js 20+ (with npm) and GitHub CLI first.\n' "$sesh_command" >&2
      exit 1
    }
  done
  node -e 'process.exit(Number(process.versions.node.split(".")[0]) >= 20 ? 0 : 1)' || {
    printf 'sesh: Node.js 20 or newer is required.\n' >&2
    exit 1
  }
  gh auth status --hostname github.com >/dev/null 2>&1 </dev/null || {
    printf 'sesh: GitHub authentication is required for this private release. Run gh auth login with an account that can access techsavvyash/clanker, then retry.\n' >&2
    exit 1
  }

  sesh_prefix=${SESH_INSTALL_PREFIX:-${HOME:?HOME must be set}/.local}
  case "$sesh_prefix" in
    /*) ;;
    *) printf 'sesh: SESH_INSTALL_PREFIX must be an absolute path.\n' >&2; exit 1 ;;
  esac
  sesh_temp_root=${TMPDIR:-/tmp}
  sesh_temp_root=${sesh_temp_root%/}
  case "$sesh_temp_root" in
    /*) ;;
    *) printf 'sesh: TMPDIR must be an absolute path.\n' >&2; exit 1 ;;
  esac
  sesh_tmp=$(mktemp -d "$sesh_temp_root/sesh-install.XXXXXXXX")
  case "$sesh_tmp" in
    "$sesh_temp_root"/sesh-install.????????) ;;
    *) printf 'sesh: unexpected temporary directory; stopping.\n' >&2; exit 1 ;;
  esac
  trap 'rm -rf -- "$sesh_tmp"' 0
  trap 'exit 1' 1 2 15
  sesh_asset="$sesh_tmp/techsavvyash-sesh-0.1.0.tgz"
  printf 'Downloading sesh 0.1.0…\n'
  gh release download sesh-v0.1.0 --repo techsavvyash/clanker \
    --pattern techsavvyash-sesh-0.1.0.tgz --dir "$sesh_tmp" </dev/null || {
    printf 'sesh: release download failed. Check access to techsavvyash/clanker and retry.\n' >&2
    exit 1
  }
  node -e '
    const fs = require("node:fs");
    const crypto = require("node:crypto");
    const actual = crypto.createHash("sha256").update(fs.readFileSync(process.argv[1])).digest("hex");
    if (actual !== "172c3025de6b7303ed936603f289162930db8e6d8acf416a2ad396919e313b7d") {
      console.error("sesh: release checksum mismatch; nothing was installed.");
      process.exit(1);
    }
  ' "$sesh_asset"
  npm install --global --prefix "$sesh_prefix" --ignore-scripts --no-audit --no-fund "$sesh_asset" </dev/null
  printf '\nsesh 0.1.0 installed in %s/bin.\n' "$sesh_prefix"
  case ":$PATH:" in
    *":$sesh_prefix/bin:"*) printf 'Run: sesh --help\n' ;;
    *) printf 'Add this directory to your PATH, then run sesh --help:\n  %s/bin\n' "$sesh_prefix" ;;
  esac
}
sesh_install
