#!/bin/sh
# Installs agent on Linux or macOS, or updates it when it is already installed: https://agent.cebecifaruk.com
#
#   curl -fsSL https://agent.cebecifaruk.com/install.sh | sh
#
# The binary goes to $AGENT_INSTALL_DIR, by default ~/.local/bin, which is added to PATH once. It is verified against
# SHA256SUMS and replaced atomically, so a failed update keeps the installed binary. Everything runs from the last line,
# so a partly downloaded script runs nothing.
set -eu

main() {
  downloads=https://agent.cebecifaruk.com/download
  dir=${AGENT_INSTALL_DIR:-$HOME/.local/bin}

  case $(uname -s) in
    Linux) os=linux ;;
    Darwin) os=macos ;;
    *) fail "$(uname -s) is not supported; on Windows, run install.ps1 in PowerShell" ;;
  esac
  arch=$(uname -m)
  # Shells under Rosetta report x86_64 on Apple Silicon, which runs the arm64 binary natively.
  [ "$(sysctl -n sysctl.proc_translated 2>/dev/null)" != 1 ] || arch=arm64
  case $os-$arch in
    linux-x86_64 | linux-aarch64 | macos-x86_64 | macos-arm64) asset=agent-$os-$arch ;;
    *) fail "there is no binary for $os $arch" ;;
  esac

  mkdir -p "$dir"
  dir=$(cd "$dir" && pwd)
  # The download is renamed over the binary, which needs both to be on the same file system.
  tmp=$(mktemp "$dir/.agent.XXXXXX")
  trap 'rm -f "$tmp"' EXIT
  trap 'exit 1' HUP INT TERM

  download "$downloads/$asset" >"$tmp"
  sum=$(download "$downloads/SHA256SUMS" | awk -v asset="$asset" '$2 == asset { print $1 }')
  [ -n "$sum" ] && [ "$(sha256 "$tmp")" = "$sum" ] || fail "the checksum of $asset does not match"
  chmod 755 "$tmp"
  version=$("$tmp" --version) || fail "the downloaded binary does not run"
  [ -e "$dir/agent" ] && action=Updated || action=Installed
  mv -f "$tmp" "$dir/agent"
  echo "$action $version in $dir/agent"

  case :$PATH: in
    *:"$dir":*) ;;
    *) add_to_path "$dir" ;;
  esac
}

# Adds a line to the startup file of the shell, unless it is already there.
add_to_path() {
  line="export PATH=\"$1:\$PATH\""
  case ${SHELL:-} in
    */zsh) rc=${ZDOTDIR:-$HOME}/.zshrc ;;
    */bash) rc=$HOME/.bashrc && [ "$os" = linux ] || rc=$HOME/.bash_profile ;;
    */fish) rc=${XDG_CONFIG_HOME:-$HOME/.config}/fish/conf.d/agent.fish line="fish_add_path \"$1\"" ;;
    *) rc=$HOME/.profile ;;
  esac
  mkdir -p "$(dirname "$rc")"
  grep -qsxF "$line" "$rc" || { printf '\n# Added by the agent installer\n%s\n' "$line" >>"$rc" && echo "Added $1 to PATH in $rc"; }
  echo "Open a new terminal to use agent"
}

download() {
  if command -v curl >/dev/null 2>&1; then
    curl --proto '=https' --tlsv1.2 -fsSL "$1"
  else
    wget -qO- "$1"
  fi
}

sha256() {
  if command -v sha256sum >/dev/null 2>&1; then sha256sum "$1"; else shasum -a 256 "$1"; fi | cut -d ' ' -f 1
}

fail() {
  echo "agent installer: $*" >&2
  exit 1
}

main
