#!/bin/sh
set -eu

version="${BIZX402_VERSION:-0.1.0}"
release_base="${BIZX402_RELEASE_BASE_URL:-https://demo-api-1.smallfishpte.com/downloads/bizx402/releases/${version}}"

case "$(uname -s)" in
  Darwin) os=darwin ;;
  Linux) os=linux ;;
  *)
    printf 'Unsupported operating system: %s\n' "$(uname -s)" >&2
    exit 1
    ;;
esac

case "$(uname -m)" in
  arm64|aarch64) arch=arm64 ;;
  x86_64|amd64) arch=amd64 ;;
  *)
    printf 'Unsupported CPU architecture: %s\n' "$(uname -m)" >&2
    exit 1
    ;;
esac

if ! command -v curl >/dev/null 2>&1; then
  printf 'curl is required to install bizx402.\n' >&2
  exit 1
fi
if ! command -v tar >/dev/null 2>&1; then
  printf 'tar is required to install bizx402.\n' >&2
  exit 1
fi

install_dir="${BIZX402_INSTALL_DIR:-}"
if [ -z "$install_dir" ]; then
  if [ -n "${XDG_BIN_HOME:-}" ]; then
    install_dir="$XDG_BIN_HOME"
  elif [ -n "${HOME:-}" ]; then
    install_dir="$HOME/.local/bin"
  else
    printf 'Set BIZX402_INSTALL_DIR because no home directory is available.\n' >&2
    exit 1
  fi
fi

archive="bizx402_${version}_${os}_${arch}.tar.gz"
temp_dir=$(mktemp -d "${TMPDIR:-/tmp}/bizx402-install.XXXXXX")
cleanup() {
  rm -rf "$temp_dir"
}
trap cleanup EXIT HUP INT TERM

curl --fail --location --silent --show-error --proto '=https' --tlsv1.2 \
  "$release_base/$archive" -o "$temp_dir/$archive"
curl --fail --location --silent --show-error --proto '=https' --tlsv1.2 \
  "$release_base/SHA256SUMS" -o "$temp_dir/SHA256SUMS"

checksum_line=$(awk -v archive="$archive" '$2 == archive { print; found = 1 } END { if (!found) exit 1 }' "$temp_dir/SHA256SUMS") || {
  printf 'No checksum was published for %s.\n' "$archive" >&2
  exit 1
}
printf '%s\n' "$checksum_line" > "$temp_dir/SHA256SUMS.selected"

if command -v sha256sum >/dev/null 2>&1; then
  (cd "$temp_dir" && sha256sum -c SHA256SUMS.selected)
elif command -v shasum >/dev/null 2>&1; then
  (cd "$temp_dir" && shasum -a 256 -c SHA256SUMS.selected)
else
  printf 'sha256sum or shasum is required to verify the download.\n' >&2
  exit 1
fi

mkdir -p "$temp_dir/unpacked" "$install_dir"
tar -xzf "$temp_dir/$archive" -C "$temp_dir/unpacked"
for binary in bizx402 bizx402-mcp; do
  if [ ! -f "$temp_dir/unpacked/$binary" ]; then
    printf 'Release archive is missing %s.\n' "$binary" >&2
    exit 1
  fi
  install -m 0755 "$temp_dir/unpacked/$binary" "$install_dir/$binary"
done

printf 'Installed bizx402 %s to %s\n' "$version" "$install_dir"
case ":${PATH:-}:" in
  *:"$install_dir":*) ;;
  *) printf 'Add %s to PATH before running bizx402.\n' "$install_dir" ;;
esac
printf 'Next: bizx402 doctor\n'
printf 'Then import your signer in a trusted terminal: bizx402 signer import\n'
