#!/bin/sh
# Installs the teler CLI on macOS or Linux:
#
#   curl -fsSL https://teler.ai/install.sh | bash
#
# It downloads the newest stable release for this computer through teler.ai's
# download links (GitHub releases of teler-ai/teler-client), checks it against
# that release's SHA256SUMS.txt, and installs it as ~/.local/bin/teler, or in
# TELER_INSTALL_DIR. It changes nothing else. For Windows, see
# https://teler.ai/en/cli.
#
# Everything runs inside main, so a partly downloaded script does nothing.

set -eu

main() {
  origin="${TELER_DOWNLOAD_ORIGIN:-https://teler.ai}"
  dir="${TELER_INSTALL_DIR:-$HOME/.local/bin}"

  case "$(uname -s)" in
    Darwin) os=mac ;;
    Linux) os=linux ;;
    *) fail "this script installs the CLI on macOS and Linux. For other systems, see $origin/en/cli" ;;
  esac
  case "$(uname -m)" in
    arm64 | aarch64) arch=arm64 ;;
    x86_64 | amd64) arch=x64 ;;
    *) fail "there is no teler CLI build for $(uname -m) processors. See $origin/en/cli" ;;
  esac
  # A shell running under Rosetta reports x86_64 on Apple silicon.
  if [ "$os" = mac ] && [ "$arch" = x64 ] &&
    [ "$(sysctl -n sysctl.proc_translated 2>/dev/null || true)" = 1 ]; then
    arch=arm64
  fi
  target="$os-$arch"

  tmp="$(mktemp -d "${TMPDIR:-/tmp}/teler-install.XXXXXX")"
  trap 'rm -rf "$tmp"' EXIT

  echo "Downloading the teler CLI for $target..."
  curl -fsSL -o "$tmp/teler" "$origin/download/cli/$target" ||
    fail "the download failed. Try again later, or download it from $origin/en/cli"
  curl -fsSL -o "$tmp/SHA256SUMS.txt" "$origin/download/cli/checksums" ||
    fail "the release checksums could not be downloaded. Try again later"

  expected="$(awk -v name="teler-$target" '$2 == name || $2 == "*" name { print $1 }' "$tmp/SHA256SUMS.txt")"
  actual="$(sha256 "$tmp/teler")"
  if [ -z "$expected" ] || [ "$expected" != "$actual" ]; then
    fail "the download does not match the release checksum. Nothing was installed; try again"
  fi

  chmod +x "$tmp/teler"
  mkdir -p "$dir"
  mv -f "$tmp/teler" "$dir/teler"
  version="$("$dir/teler" --version 2>/dev/null)" ||
    fail "teler was installed in $dir but does not start on this computer"
  echo "$version is installed in $dir."

  case ":$PATH:" in
    *":$dir:"*) ;;
    *)
      case "${SHELL:-}" in
        */zsh) rc='~/.zshrc' ;;
        */bash) rc='~/.bashrc' ;;
        *) rc='~/.profile' ;;
      esac
      echo "Add that folder to your PATH, then open a new terminal:"
      echo "  echo 'export PATH=\"$dir:\$PATH\"' >> $rc"
      ;;
  esac
  echo "Then sign in with: teler auth login"
}

sha256() {
  if command -v sha256sum >/dev/null 2>&1; then
    sha256sum "$1" | awk '{ print $1 }'
  elif command -v shasum >/dev/null 2>&1; then
    shasum -a 256 "$1" | awk '{ print $1 }'
  else
    fail "sha256sum or shasum is needed to check the download"
  fi
}

fail() {
  echo "teler install: $1" >&2
  exit 1
}

main "$@"
