#!/bin/sh
set -eu

if [ "${1:-}" = "--help" ]; then
  printf '%s\n' 'Install Testbay CLI for macOS/Linux (requires Node.js 22+, npm, curl and tar).' 'Default location: ~/.local/share/testbay-cli; command: ~/.local/bin/testbay.'
  exit 0
fi
if [ "$#" -gt 0 ]; then printf '%s\n' 'Unknown option. Use --help.' >&2; exit 1; fi

case "$(uname -s)" in Darwin|Linux) ;; *) printf '%s\n' 'Use the manual setup at https://testbay.dev/cli for this operating system.' >&2; exit 1 ;; esac
for dependency in node npm curl tar; do
  command -v "$dependency" >/dev/null 2>&1 || { printf 'Please install %s first.\n' "$dependency" >&2; exit 1; }
done
node -e 'if (Number(process.versions.node.split(".")[0]) < 22) process.exit(1)' || { printf '%s\n' 'Please install Node.js 22 or newer first.' >&2; exit 1; }

app_root="${TESTBAY_INSTALL_ROOT:-$HOME/.local/share/testbay-cli}"
bin_dir="${TESTBAY_BIN_DIR:-$HOME/.local/bin}"
case "$app_root:$bin_dir" in /*:/*) ;; *) printf '%s\n' 'Installation directories must be absolute paths.' >&2; exit 1 ;; esac
if [ -e "$bin_dir/testbay" ] || [ -L "$bin_dir/testbay" ]; then
  if [ ! -L "$bin_dir/testbay" ]; then printf '%s\n' 'An existing testbay command would be overwritten. Move it first.' >&2; exit 1; fi
  case "$(readlink "$bin_dir/testbay")" in "$app_root"/releases/*/src/cli.mjs) ;; *) printf '%s\n' 'The existing testbay command belongs to another installation. Move it first.' >&2; exit 1 ;; esac
fi

umask 077
mkdir -p "$app_root/releases" "$bin_dir"
release_dir=$(mktemp -d "$app_root/releases/install.XXXXXXXX")
completed=false
cleanup() {
  if [ "$completed" = false ]; then rm -rf "$release_dir"; fi
}
trap cleanup EXIT
trap 'exit 1' HUP INT TERM

printf '%s\n' 'Downloading Testbay CLI…'
curl --fail --silent --show-error --location --proto '=https' --proto-redir '=https' --connect-timeout 15 --max-time 120 https://testbay.dev/downloads/testbay-cli.tgz -o "$release_dir/package.tgz"
tar -xzf "$release_dir/package.tgz" -C "$release_dir"
rm "$release_dir/package.tgz"
printf '%s\n' 'Installing dependencies…'
(cd "$release_dir" && npm ci --omit=dev --ignore-scripts --no-audit --no-fund)
chmod 755 "$release_dir/src/cli.mjs"
node "$release_dir/src/cli.mjs" --version >/dev/null
# Install without sudo; keep previous release directories for manual recovery.
ln -sfn "$release_dir/src/cli.mjs" "$bin_dir/testbay"
completed=true
printf '\n%s\n' 'Testbay CLI installed.'
case ":$PATH:" in
  *":$bin_dir:"*) printf '%s\n' 'Run: testbay login' ;;
  *) printf 'Add this directory to your shell PATH: %s\nThen run: testbay login\nOr run directly: "%s/testbay" login\n' "$bin_dir" "$bin_dir" ;;
esac
