#!/bin/sh
set -eu

repository="yoloyash/overtchat"
cli_version="0.4.0"

say() {
  printf '%s\n' "$*"
}

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

case "$(uname -s)" in
  Linux) platform="linux"; checksum_command="sha256sum" ;;
  Darwin) platform="darwin"; checksum_command="shasum" ;;
  *) fail "the managed installer supports Linux and macOS" ;;
esac

checksum() {
  if [ "$platform" = "darwin" ]; then shasum -a 256 "$1"; else sha256sum "$1"; fi
}

case "$(uname -m)" in
  x86_64|amd64) architecture="amd64" ;;
  aarch64|arm64) architecture="arm64" ;;
  *) fail "unsupported CPU architecture: $(uname -m)" ;;
esac

for command in curl "$checksum_command" awk install mktemp; do
  command -v "$command" >/dev/null 2>&1 || fail "required command not found: $command"
done

asset="overtchat-$platform-$architecture"
release_url="https://github.com/$repository/releases/download/cli-v$cli_version"
temporary_directory=$(mktemp -d)
trap 'rm -rf "$temporary_directory"' EXIT HUP INT TERM

say "Downloading OvertChat $cli_version..."
curl --proto '=https' --tlsv1.2 -fsSLo "$temporary_directory/$asset" \
  "$release_url/$asset"
curl --proto '=https' --tlsv1.2 -fsSLo "$temporary_directory/checksums.txt" \
  "$release_url/overtchat-checksums.txt"

expected=$(
  awk -v asset="$asset" '$2 == asset || $2 == "*" asset { print $1; exit }' \
    "$temporary_directory/checksums.txt"
)
[ -n "$expected" ] || fail "the release checksum for $asset is missing"
actual=$(checksum "$temporary_directory/$asset" | awk '{ print $1 }')
[ "$actual" = "$expected" ] || fail "the downloaded binary failed checksum verification"

install_directory="${HOME:?}/.local/bin"
install_path="$install_directory/overtchat"
mkdir -p "$install_directory"
install -m 0755 "$temporary_directory/$asset" "$install_path"

say "Installed the overtchat command at $install_path"
case ":$PATH:" in
  *":$install_directory:"*) ;;
  *)
    say "Add $install_directory to PATH to run overtchat from any shell."
    case "${SHELL:-}" in
      */fish) say 'Run: fish_add_path "$HOME/.local/bin"' ;;
      */zsh) say 'Add to ~/.zshrc: export PATH="$HOME/.local/bin:$PATH"'; say 'Then run: source ~/.zshrc' ;;
      *) say 'Add to your shell profile: export PATH="$HOME/.local/bin:$PATH"'; say 'Then open a new terminal.' ;;
    esac
    ;;
esac

# The installer consumes stdin under curl | sh. Reopen the actual terminal
# device for setup; Bun cannot reliably poll the /dev/tty alias on macOS.
terminal=""
if command -v tty >/dev/null 2>&1; then
  if terminal=$(tty <&2 2>/dev/null); then
    :
  elif terminal=$(tty <&1 2>/dev/null); then
    :
  else
    terminal=""
  fi
fi

case "$terminal" in
  /dev/*)
    if [ -c "$terminal" ] && ( : <>"$terminal" ) 2>/dev/null; then
      exec "$install_path" setup <>"$terminal"
    fi
    ;;
esac

if [ -n "$terminal" ]; then
  say "Could not open the controlling terminal at $terminal."
fi

say "Run $install_path setup in an interactive terminal to finish."
