#!/bin/bash

# Install or update OpenCode CLI on Debian/Ubuntu systems.
set -euo pipefail

# Allow running directly as root (no sudo needed) or as a normal user.
if [[ "${EUID}" -eq 0 ]]; then
  sudo() { while [[ "$1" == -* ]]; do shift; done; "$@"; }
  export -f sudo
fi

echo "==> Ensuring Node.js dependencies"
sudo apt-get update
sudo apt-get install -y --no-install-recommends ca-certificates curl

if ! command -v node >/dev/null 2>&1; then
  echo "==> Installing Node.js current for npm-based OpenCode install"
  curl -fsSL https://deb.nodesource.com/setup_current.x | sudo -E bash -
  sudo apt-get install -y --no-install-recommends nodejs
else
  echo "==> Node.js already present; refreshing NodeSource current channel"
  curl -fsSL https://deb.nodesource.com/setup_current.x | sudo -E bash -
  sudo apt-get install -y --no-install-recommends nodejs
fi

if command -v opencode >/dev/null 2>&1; then
  echo "==> Updating OpenCode CLI"
else
  echo "==> Installing OpenCode CLI"
fi

sudo npm install -g opencode-ai

opencode_binary="$(command -v opencode || true)"
if [[ -z "${opencode_binary}" ]]; then
  if command -v opencode.exe >/dev/null 2>&1; then
    opencode_binary="$(command -v opencode.exe)"
  fi
fi

if [[ -z "${opencode_binary}" ]]; then
  npm_prefix="$(npm config get prefix)"
  if [[ -n "${npm_prefix}" && -x "${npm_prefix}/bin/opencode" ]]; then
    opencode_binary="${npm_prefix}/bin/opencode"
  fi
fi

if [[ -n "${opencode_binary}" ]]; then
  echo "==> OpenCode binary installed: ${opencode_binary}"
else
  echo "opencode command was not installed correctly."
  exit 1
fi
