#!/bin/sh
set -eu

BASE_URL='https://api.ecdsa.fail'
BIN_DIR="${ECDSAFAIL_BIN_DIR:-$HOME/.local/bin}"
LIB_DIR="${ECDSAFAIL_LIB_DIR:-$HOME/.local/share/ecdsafail}"
CLI_PATH="$LIB_DIR/ecdsafail.js"
CLI_BIN="$BIN_DIR/ecdsafail"

say() { printf '%s\n' "$1"; }
fail() { printf 'error: %s\n' "$1" >&2; exit 1; }
shell_quote() { printf "'%s'" "$(printf '%s' "$1" | sed "s/'/'\\''/g")"; }
curl_file() {
  url=$1
  output=$2
  if curl --retry 8 --retry-all-errors --connect-timeout 20 --tls-max 1.2 -fsSL "$url" -o "$output"; then return 0; fi
  if curl --retry 8 --connect-timeout 20 --tls-max 1.2 -fsSL "$url" -o "$output"; then return 0; fi
  curl --retry 8 --connect-timeout 20 -fsSL "$url" -o "$output"
}

command -v curl >/dev/null 2>&1 || fail 'curl is required to install ECDSA Fail CLI'
command -v sed >/dev/null 2>&1 || fail 'sed is required to install ECDSA Fail CLI'

if command -v bun >/dev/null 2>&1; then
  BUN_PATH=$(command -v bun)
else
  command -v bash >/dev/null 2>&1 || fail 'bash is required to install Bun'
  say 'Bun is required for the ECDSA Fail CLI. Installing Bun...'
  curl -fsSL https://bun.sh/install | bash
  if [ -x "$HOME/.bun/bin/bun" ]; then
    BUN_PATH="$HOME/.bun/bin/bun"
  elif command -v bun >/dev/null 2>&1; then
    BUN_PATH=$(command -v bun)
  else
    fail 'Bun install finished, but bun was not found. Add ~/.bun/bin to PATH and rerun this installer.'
  fi
fi

mkdir -p "$BIN_DIR" "$LIB_DIR"
TMP_FILE="$CLI_PATH.tmp.$$"
trap 'rm -f "$TMP_FILE"' EXIT HUP INT TERM
say "Downloading ECDSA Fail CLI from $BASE_URL..."
curl_file "$BASE_URL/cli/ecdsafail.js" "$TMP_FILE"
[ -s "$TMP_FILE" ] || fail "downloaded CLI payload is empty"
mv "$TMP_FILE" "$CLI_PATH"

{
  printf '%s\n' '#!/bin/sh'
  printf 'if [ -z "${ECDSAFAIL_API_URL:-}" ]; then export ECDSAFAIL_API_URL=%s; fi\n' "$(shell_quote "$BASE_URL")"
  printf 'if [ -z "${ECDSAFAIL_BENCHMARK_REF:-}" ]; then export ECDSAFAIL_BENCHMARK_REF=%s; fi\n' "$(shell_quote '1ffb695a-309b-46b6-a728-2f97d8c7be74')"
  printf 'exec %s %s "$@"\n' "$(shell_quote "$BUN_PATH")" "$(shell_quote "$CLI_PATH")"
} > "$CLI_BIN"
chmod +x "$CLI_BIN"

say "Installed ecdsafail to $CLI_BIN"
if [ "${ECDSAFAIL_INSTALL_SKILL:-1}" != "0" ]; then
  "$CLI_BIN" install-skill
fi

say 'CLI telemetry is enabled after login. Disable it with: ecdsafail config --telemetry disabled'
if ! command -v ecdsafail >/dev/null 2>&1; then
  say "Add $BIN_DIR to your PATH to run ecdsafail from any shell."
fi
say 'Done. Try: ecdsafail --help'
