#!/bin/sh
set -eu

main() {
  command -v curl >/dev/null 2>&1 || { printf '%s\n' 'curl is required.' >&2; exit 1; }
  case $(uname -s) in
    Darwin) os=darwin ;;
    Linux) os=linux ;;
    *) printf '%s\n' 'Supported systems: macOS and Linux.' >&2; exit 1 ;;
  esac
  case $(uname -m) in
    arm64|aarch64) arch=arm64 ;;
    x86_64|amd64) arch=x64 ;;
    *) printf '%s\n' 'Supported architectures: arm64 and x64.' >&2; exit 1 ;;
  esac
  if command -v sha256sum >/dev/null 2>&1; then
    hasher=sha256sum
  elif command -v shasum >/dev/null 2>&1; then
    hasher=shasum
  else
    printf '%s\n' 'sha256sum or shasum is required.' >&2
    exit 1
  fi
  : "${HOME:?HOME is required}"
  base=https://todos.sh
  platform=$os-$arch
  temp=$(mktemp -d "${TMPDIR:-/tmp}/todos.XXXXXXXX")
  stage=
  trap 'rm -f "$temp/manifest.json" "$temp/todos"; rmdir "$temp"; if [ -n "$stage" ]; then rm -f "$stage"; fi' 0
  trap 'exit 1' 1 2 3 15
  curl --proto '=https' --tlsv1.2 -fsSL "$base/dl/manifest.json" -o "$temp/manifest.json"
  version=$(awk -F '"' '{ for (i = 2; i < NF; i += 2) if ($i == "version") print $(i + 2) }' "$temp/manifest.json")
  checksum=$(awk -F '"' -v key="$platform" '{ for (i = 2; i < NF; i += 2) if ($i == key) print $(i + 2) }' "$temp/manifest.json")
  case $version in
    ''|*[!0-9A-Za-z.-]*|.*|-*) printf '%s\n' 'Invalid release version.' >&2; exit 1 ;;
  esac
  case $checksum in
    ''|*[!a-f0-9]*) printf '%s\n' 'Missing or invalid release checksum.' >&2; exit 1 ;;
  esac
  [ "${#checksum}" -eq 64 ] || { printf '%s\n' 'Invalid checksum length.' >&2; exit 1; }
  curl --proto '=https' --tlsv1.2 -fsSL "$base/dl/$version/$platform" -o "$temp/todos"
  if [ "$hasher" = sha256sum ]; then
    actual=$(sha256sum "$temp/todos")
  else
    actual=$(shasum -a 256 "$temp/todos")
  fi
  actual=${actual%% *}
  [ "$actual" = "$checksum" ] || { printf '%s\n' 'Checksum failed. The installed binary was not changed.' >&2; exit 1; }
  dest=${TODOS_INSTALL_DIR:-$HOME/.local/bin}
  mkdir -p "$dest"
  stage=$(mktemp "$dest/.todos.XXXXXXXX")
  cp "$temp/todos" "$stage"
  chmod 755 "$stage"
  mv -f "$stage" "$dest/todos"
  stage=
  printf 'Installed todos %s to %s/todos\n' "$version" "$dest"
  case :$PATH: in
    *:"$dest":*) ;;
    *) printf '%s\n' 'Add this line to your shell profile, then open a new terminal:'; printf '  export PATH="%s:%s"\n' "$dest" "\$PATH" ;;
  esac
  printf '%s\n' 'Run: todos auth login'
}

main "$@"
