#!/bin/sh
set -eu

DOWNLOADS_URL="https://startroutine.app/downloads/cli"
VERSION_PATTERN='^[0-9]+\.[0-9]+\.[0-9]+$'

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

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

has() {
  command -v "$1" > /dev/null 2>&1
}

detect_os() {
  case "$(uname -s)" in
    Darwin) echo darwin ;;
    Linux) echo linux ;;
    *) unsupported_platform "$(uname -s)" ;;
  esac
}

detect_arch() {
  case "$(uname -m)" in
    x86_64 | amd64)
      if [ "$(sysctl -n sysctl.proc_translated 2> /dev/null || echo 0)" = 1 ]; then
        echo arm64
      else
        echo amd64
      fi
      ;;
    arm64 | aarch64) echo arm64 ;;
    *) unsupported_platform "$(uname -m)" ;;
  esac
}

unsupported_platform() {
  fail "startroutine isn't built for $1. The install script supports macOS and Linux on amd64 and arm64.
On Windows, download startroutine_<version>_windows_<amd64|arm64>.zip from $DOWNLOADS_URL/<version>/"
}

check_tools() {
  if has curl; then
    downloader=curl
  elif has wget; then
    downloader=wget
  else
    fail "curl or wget is needed to download startroutine."
  fi

  has tar || fail "tar is needed to unpack startroutine."

  if has sha256sum; then
    hasher="sha256sum"
  elif has shasum; then
    hasher="shasum -a 256"
  else
    fail "sha256sum or shasum is needed to verify the download."
  fi
}

fetch() {
  if [ "$downloader" = curl ]; then
    curl -fsSL --proto '=https' --tlsv1.2 --retry 3 -o "$2" "$1"
  else
    wget -q --https-only -O "$2" "$1"
  fi || fail "Couldn't download $1
${3:-startroutine.app may be waking up or briefly down. Try again in a minute.}"
}

resolve_version() {
  if [ -n "${CADENCE_VERSION:-}" ]; then
    requested="${CADENCE_VERSION#v}"
    printf '%s' "$requested" | grep -Eq "$VERSION_PATTERN" ||
      fail "CADENCE_VERSION must look like 1.2.0, not '$CADENCE_VERSION'."
    echo "$requested"
    return
  fi

  fetch "$DOWNLOADS_URL/latest.txt" "$tmp/latest.txt"
  latest="$(tr -d '[:space:]' < "$tmp/latest.txt")"
  printf '%s' "$latest" | grep -Eq "$VERSION_PATTERN" ||
    fail "$DOWNLOADS_URL/latest.txt didn't contain a version."
  echo "$latest"
}

missing_release_hint() {
  if [ -n "${CADENCE_VERSION:-}" ]; then
    echo "Check that startroutine $version exists, or unset CADENCE_VERSION to install the latest release."
  fi
}

verify_checksum() {
  expected="$(awk -v name="$1" '$2 == name { print $1 }' "$tmp/checksums.txt")"
  [ -n "$expected" ] || fail "checksums.txt has no entry for $1."

  actual="$($hasher "$tmp/$1" | awk '{ print $1 }')"
  [ "$actual" = "$expected" ] || fail "The checksum of $1 doesn't match checksums.txt, so nothing was installed."
}

install_binary() {
  mkdir -p "$install_dir" || fail "Couldn't create $install_dir."
  staged="$install_dir/.startroutine.$$"
  cp "$tmp/startroutine" "$staged" || fail "Couldn't write to $install_dir. Set CADENCE_INSTALL_DIR to a directory you own."
  chmod 755 "$staged"
  mv -f "$staged" "$install_dir/startroutine"
}

print_path_hint() {
  case ":$PATH:" in
    *":$install_dir:"*) return ;;
  esac

  say ""
  say "$install_dir isn't on your PATH. To add it, run:"
  case "$(basename "${SHELL:-sh}")" in
    zsh) say "  echo 'export PATH=\"$install_dir:\$PATH\"' >> ~/.zshrc && exec zsh" ;;
    bash) say "  echo 'export PATH=\"$install_dir:\$PATH\"' >> ~/.bashrc && exec bash" ;;
    fish) say "  fish_add_path $install_dir" ;;
    *) say "  export PATH=\"$install_dir:\$PATH\"" ;;
  esac
}

main() {
  os="$(detect_os)"
  arch="$(detect_arch)"
  check_tools

  install_dir="${CADENCE_INSTALL_DIR:-$HOME/.local/bin}"
  tmp="$(mktemp -d)"
  trap 'rm -rf "$tmp"' EXIT
  trap 'exit 1' INT TERM

  say "Contacting startroutine.app..."
  version="$(resolve_version)"
  archive="startroutine_${version}_${os}_${arch}.tar.gz"

  say "Downloading startroutine ${version} for ${os}/${arch}..."
  fetch "$DOWNLOADS_URL/$version/checksums.txt" "$tmp/checksums.txt" "$(missing_release_hint)"
  fetch "$DOWNLOADS_URL/$version/$archive" "$tmp/$archive"
  verify_checksum "$archive"
  say "Checksum verified."

  tar -xzf "$tmp/$archive" -C "$tmp" startroutine || fail "Couldn't unpack $archive."
  install_binary
  say "Installed startroutine to $install_dir/startroutine"

  "$install_dir/startroutine" version > /dev/null || fail "The installed binary didn't run."
  print_path_hint
  say ""
  say "Run \`startroutine\` to start."
}

main "$@"
