#!/bin/bash
# Install tsv — the tsvsheet CLI (https://tsvsheet.com) — from the latest
# GitHub release, verifying its sha256 against the release's checksums.txt.
#
# Usage:
#   curl -fsSL https://tsv.sh | bash
#   curl -fsSL https://tsv.sh | BINDIR="${HOME}/bin" bash
# Where:
#   BINDIR is the install directory. Default: /usr/local/bin when writable,
#   otherwise ~/.local/bin.
#
# Windows: scoop bucket add tsvsheet https://github.com/tsvsheet/scoop-bucket
#          scoop install tsv
# Homebrew (adds completions and the man page): brew install tsvsheet/tap/tsv

set -o errexit
set -o nounset
set -o pipefail

exec 3>&1 4>&2

REPO=tsvsheet/tsvsheet.go
NAME=tsv

detect-os() {
  case "$(uname -s)" in
    Darwin) printf 'darwin' ;;
    Linux) printf 'linux' ;;
    *)
      printf >&4 '✗ unsupported OS %s — see https://tsvsheet.com/install/\n' "$(uname -s)"
      return 1
      ;;
  esac
}

detect-arch() {
  case "$(uname -m)" in
    x86_64 | amd64) printf 'amd64' ;;
    arm64 | aarch64) printf 'arm64' ;;
    *)
      printf >&4 '✗ unsupported architecture %s — prebuilt archives: https://github.com/%s/releases\n' "$(uname -m)" "${REPO}"
      return 1
      ;;
  esac
}

# The latest tag, read from the release redirect — no API, no rate limit.
latest-tag() {
  local effective
  effective="$(curl -fsSLI -o /dev/null -w '%{url_effective}' "https://github.com/${REPO}/releases/latest")"
  printf '%s' "${effective##*/}"
}

sha256-check() {
  command -v sha256sum >/dev/null 2>&1 && {
    sha256sum -c - >/dev/null
    return 0
  }
  shasum -a 256 -c - >/dev/null
}

OS="$(detect-os)"
ARCH="$(detect-arch)"
TAG="$(latest-tag)"
VERSION=${TAG#v}
ARCHIVE="${NAME}-${VERSION}-${OS}-${ARCH}.tar.gz"
BASE="https://github.com/${REPO}/releases/download/${TAG}"

[[ ${BINDIR:-} ]] || {
  BINDIR=/usr/local/bin
  [[ -w ${BINDIR} ]] || BINDIR="${HOME}/.local/bin"
}

TMP_DIR="$(mktemp -d)"
trap 'rm -rf "${TMP_DIR}"' EXIT

printf >&3 '▸ Installing %s %s (%s-%s) to %s\n' "${NAME}" "${TAG}" "${OS}" "${ARCH}" "${BINDIR}"

curl -fsSL "${BASE}/${ARCHIVE}" -o "${TMP_DIR}/${ARCHIVE}"
curl -fsSL "${BASE}/checksums.txt" -o "${TMP_DIR}/checksums.txt"

cd "${TMP_DIR}"
grep -- " ${ARCHIVE}\$" checksums.txt | sha256-check || {
  printf >&4 '✗ checksum mismatch for %s — aborting\n' "${ARCHIVE}"
  exit 1
}

tar -xzf "${ARCHIVE}"
mkdir -p "${BINDIR}"
install -m 0755 "${NAME}-${OS}-${ARCH}" "${BINDIR}/${NAME}"

[[ -f "man/${NAME}.1" ]] && {
  MAN_DIR="${HOME}/.local/share/man/man1"
  mkdir -p "${MAN_DIR}"
  install -m 0644 "man/${NAME}.1" "${MAN_DIR}/${NAME}.1"
} || true

printf >&3 '✓ %s\n' "$("${BINDIR}/${NAME}" --version)"
case ":${PATH}:" in
  *":${BINDIR}:"*) ;;
  *) printf >&3 '▸ add %s to your PATH\n' "${BINDIR}" ;;
esac
printf >&3 '▸ shell completion: source <(%s completion bash)   # or zsh / fish\n' "${NAME}"

exit 0
