#!/usr/bin/env sh
set -eu

taproom_base_url="${TAPROOM_INSTALL_BASE_URL:-https://taproom.aquilainteractive.io}"
manifest_url="${taproom_base_url%/}/api/downloads/taproom-cli/latest/manifest.json"

require_command() {
  if ! command -v "$1" >/dev/null 2>&1; then
    echo "taproom installer: required command not found: $1" >&2
    exit 1
  fi
}

require_command curl
require_command awk
require_command sed

case "$(uname -s)" in
  Darwin) taproom_os="darwin" ;;
  Linux) taproom_os="linux" ;;
  *) echo "taproom installer: unsupported operating system: $(uname -s)" >&2; exit 1 ;;
esac

case "$(uname -m)" in
  arm64 | aarch64) taproom_arch="arm64" ;;
  x86_64 | amd64) taproom_arch="amd64" ;;
  *) echo "taproom installer: unsupported architecture: $(uname -m)" >&2; exit 1 ;;
esac

platform="${taproom_os}-${taproom_arch}"
manifest="$(curl -fsSL "$manifest_url")"
version="$(printf '%s\n' "$manifest" | sed -n 's/.*"version"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' | head -n 1)"
asset="$(printf '%s\n' "$manifest" | awk -v key="\"${platform}\"" '$0 ~ key { found=1 } found { print } found && /}/ { exit }')"
url="$(printf '%s\n' "$asset" | sed -n 's/.*"url"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' | head -n 1)"
expected_sha="$(printf '%s\n' "$asset" | sed -n 's/.*"sha256"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' | head -n 1)"
expected_size="$(printf '%s\n' "$asset" | sed -n 's/.*"size"[[:space:]]*:[[:space:]]*\([0-9][0-9]*\).*/\1/p' | head -n 1)"

if [ -z "$version" ] || [ -z "$url" ] || [ -z "$expected_sha" ] || [ -z "$expected_size" ]; then
  echo "taproom installer: release manifest does not contain a valid ${platform} asset" >&2
  exit 1
fi

install_dir="${TAPROOM_INSTALL_DIR:-$HOME/.local/bin}"
mkdir -p "$install_dir"
temp_file="$(mktemp "${install_dir}/.taproom.XXXXXX")"
trap 'rm -f "$temp_file"' EXIT HUP INT TERM
curl -fsSL "$url" -o "$temp_file"

actual_size="$(wc -c < "$temp_file" | tr -d '[:space:]')"
if [ "$actual_size" != "$expected_size" ]; then
  echo "taproom installer: downloaded size ${actual_size} does not match manifest size ${expected_size}" >&2
  exit 1
fi

if command -v shasum >/dev/null 2>&1; then
  actual_sha="$(shasum -a 256 "$temp_file" | awk '{print $1}')"
elif command -v sha256sum >/dev/null 2>&1; then
  actual_sha="$(sha256sum "$temp_file" | awk '{print $1}')"
else
  echo "taproom installer: shasum or sha256sum is required to verify the download" >&2
  exit 1
fi

if [ "$actual_sha" != "$expected_sha" ]; then
  echo "taproom installer: downloaded SHA-256 does not match the release manifest" >&2
  exit 1
fi

chmod 755 "$temp_file"
downloaded_version="$("$temp_file" --sdk-version)"
if [ "$downloaded_version" != "$version" ]; then
  echo "taproom installer: downloaded binary reports ${downloaded_version}, expected ${version}" >&2
  exit 1
fi

mv -f "$temp_file" "${install_dir}/taproom"
trap - EXIT HUP INT TERM

case ":$PATH:" in
  *:"$install_dir":*) ;;
  *)
    profile="$HOME/.profile"
    case "${SHELL:-}" in
      */zsh) profile="$HOME/.zshrc" ;;
      */bash) profile="$HOME/.bashrc" ;;
    esac
    marker="# Taproom CLI"
    if ! grep -F "$marker" "$profile" >/dev/null 2>&1; then
      {
        printf '\n%s\n' "$marker"
        printf 'export PATH="$HOME/.local/bin:$PATH"\n'
      } >> "$profile"
    fi
    echo "Added ${install_dir} to PATH in ${profile}. Open a new terminal to use taproom."
    ;;
esac

echo "Taproom CLI ${version} installed at ${install_dir}/taproom"
