#!/usr/bin/env bash
# Filename: codex-install.sh
# Ensures `codex` and `rg` are installed in /usr/local/bin.
# Checks installed versions via `codex --version` and `rg --version`,
# compares against the latest GitHub release tags, and only installs
# when missing or older than the latest available release.
# Detects platform using `uname` and `arch` and downloads matching
# release artifacts for Linux/Darwin and x86_64/arm64.

set -euo pipefail

REPO="openai/codex"
API_URL="https://api.github.com/repos/${REPO}/releases/latest"
INSTALL_PATH="/usr/local/bin/codex"
RG_REPO="BurntSushi/ripgrep"
RG_API_URL="https://api.github.com/repos/${RG_REPO}/releases/latest"
RG_INSTALL_PATH="/usr/local/bin/rg"

if [[ "${EUID:-$(id -u)}" -ne 0 ]]; then
  echo "Error: this script must be run as root." >&2
  exit 1
fi

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

need_cmd wget
need_cmd tar
need_cmd mktemp
need_cmd install
need_cmd uname
need_cmd arch

tmp_dir=""
rg_tmp_dir=""
cleanup() {
  [[ -n "$tmp_dir" ]] && rm -rf "$tmp_dir"
  [[ -n "$rg_tmp_dir" ]] && rm -rf "$rg_tmp_dir"
}
trap cleanup EXIT

extract_version() {
  # Extract first version-like token from arbitrary text.
  echo "$1" | grep -Eo '[0-9]+([.][0-9]+)+' | head -n1 || true
}

normalize_version() {
  echo "$1" | sed 's/^v//'
}

release_version_from_tag() {
  local tag extracted
  tag="$1"
  extracted="$(extract_version "$tag")"
  if [[ -n "$extracted" ]]; then
    echo "$extracted"
  else
    normalize_version "$tag"
  fi
}

version_cmp() {
  # Echoes: -1 (a<b), 0 (a==b), 1 (a>b)
  local a b first
  a="$(normalize_version "$1")"
  b="$(normalize_version "$2")"
  if [[ "$a" == "$b" ]]; then
    echo 0
    return
  fi
  first="$(printf '%s\n%s\n' "$a" "$b" | sort -V | head -n1)"
  if [[ "$first" == "$a" ]]; then
    echo -1
  else
    echo 1
  fi
}

raw_os="$(uname -s)"
raw_arch="$(arch)"

case "$raw_os" in
  Linux)
    codex_os="unknown-linux-musl"
    rg_os="unknown-linux"
    ;;
  Darwin)
    codex_os="apple-darwin"
    rg_os="apple-darwin"
    ;;
  *)
    echo "Error: unsupported OS '${raw_os}'. Supported: Linux, Darwin." >&2
    exit 1
    ;;
esac

case "$raw_arch" in
  x86_64|amd64)
    codex_arch="x86_64"
    rg_arch="x86_64"
    ;;
  arm64|aarch64)
    codex_arch="aarch64"
    rg_arch="aarch64"
    ;;
  *)
    echo "Error: unsupported architecture '${raw_arch}'. Supported: x86_64, arm64." >&2
    exit 1
    ;;
esac

if [[ "$codex_arch" == "aarch64" ]]; then
  codex_arch_regex="(aarch64|arm64)"
else
  codex_arch_regex="$codex_arch"
fi
codex_asset_regex="codex-${codex_arch_regex}-${codex_os}\\.tar\\.gz$"

if [[ "$raw_os" == "Linux" ]]; then
  if [[ "$rg_arch" == "x86_64" ]]; then
    rg_asset_regex="ripgrep-.*-x86_64-unknown-linux-(musl|gnu)\\.tar\\.gz$"
  else
    rg_asset_regex="ripgrep-.*-aarch64-unknown-linux-(gnu|musl)\\.tar\\.gz$"
  fi
else
  rg_asset_regex="ripgrep-.*-${rg_arch}-${rg_os}\\.tar\\.gz$"
fi

echo "Detected platform: os=${raw_os}, arch=${raw_arch}"

release_json="$(wget -qO- "$API_URL")"

if command -v jq >/dev/null 2>&1; then
  latest_version="$(echo "$release_json" | jq -r '.tag_name // empty' | head -n1)"
  download_url="$(
    echo "$release_json" \
      | jq -r --arg re "$codex_asset_regex" '.assets[] | select(.name | test($re)) | .browser_download_url' \
      | head -n1
  )"
else
  # Fallback parser if jq is unavailable.
  latest_version="$(
    echo "$release_json" \
      | sed -n 's/.*"tag_name"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' \
      | head -n1
  )"
  download_url="$(
    echo "$release_json" \
      | sed -n 's/.*"browser_download_url"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' \
      | grep -E "${codex_asset_regex}" \
      | head -n1
  )"
fi

if [[ -z "${latest_version:-}" ]]; then
  echo "Error: could not determine latest release version for ${REPO}." >&2
  exit 1
fi

if [[ -z "${download_url:-}" ]]; then
  echo "Error: could not find codex asset matching '${codex_asset_regex}' in latest release of ${REPO}." >&2
  exit 1
fi

latest_version="$(release_version_from_tag "$latest_version")"
installed_version=""
if command -v codex >/dev/null 2>&1; then
  installed_version="$(extract_version "$(codex --version 2>/dev/null || true)")"
fi

if [[ -n "$installed_version" ]]; then
  installed_version="$(normalize_version "$installed_version")"
  cmp_result="$(version_cmp "$installed_version" "$latest_version")"
  should_install_codex=true
  if [[ "$cmp_result" -eq 0 ]]; then
    echo "codex ${installed_version} is already the latest version."
    should_install_codex=false
  fi
  if [[ "$cmp_result" -gt 0 ]]; then
    echo "Installed codex (${installed_version}) is newer than latest GitHub release (${latest_version}); skipping install."
    should_install_codex=false
  fi
  if [[ "$should_install_codex" == true ]]; then
    echo "Updating codex from ${installed_version} to ${latest_version}..."
  fi
else
  should_install_codex=true
  echo "codex is not currently installed or version is unreadable; installing latest (${latest_version})..."
fi

if [[ "$should_install_codex" == true ]]; then
  tmp_dir="$(mktemp -d)"

  codex_tarball_name="$(basename "$download_url")"
  tarball_path="${tmp_dir}/${codex_tarball_name}"

  echo "Downloading: $download_url"
  wget -qO "$tarball_path" "$download_url"

  # Extract tarball and copy codex binary into current directory.
  tar -xzf "$tarball_path" -C "$tmp_dir"

  codex_path="$(
    find "$tmp_dir" -type f \( -name "codex" -o -name "codex-*" \) \
      -perm -u+x | head -n1 || true
  )"
  if [[ -z "$codex_path" ]]; then
    codex_path="$(
      find "$tmp_dir" -type f \( -name "codex" -o -name "codex-*" \) \
      | head -n1 || true
    )"
  fi

  if [[ -z "$codex_path" ]]; then
    echo "Error: could not find 'codex' binary in extracted archive." >&2
    exit 1
  fi

  if [[ -e "$INSTALL_PATH" ]]; then
    rm -f "$INSTALL_PATH"
  fi

  install -o root -g root -m 755 "$codex_path" "$INSTALL_PATH"

  echo "Done. Installed ${INSTALL_PATH} (version ${latest_version})"
fi

rg_release_json="$(wget -qO- "$RG_API_URL")"

if command -v jq >/dev/null 2>&1; then
  rg_latest_version="$(echo "$rg_release_json" | jq -r '.tag_name // empty' | head -n1)"
  rg_download_url="$(
    echo "$rg_release_json" \
      | jq -r '.assets[] | .browser_download_url' \
      | grep -E "${rg_asset_regex}" \
      | head -n1
  )"
else
  rg_latest_version="$(
    echo "$rg_release_json" \
      | sed -n 's/.*"tag_name"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' \
      | head -n1
  )"
  rg_download_url="$(
    echo "$rg_release_json" \
      | sed -n 's/.*"browser_download_url"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' \
      | grep -E "${rg_asset_regex}" \
      | head -n1
  )"
fi

if [[ -z "${rg_latest_version:-}" ]]; then
  echo "Error: could not determine latest release version for ${RG_REPO}." >&2
  exit 1
fi

if [[ -z "${rg_download_url:-}" ]]; then
  echo "Error: could not find ripgrep asset matching '${rg_asset_regex}' in latest release of ${RG_REPO}." >&2
  exit 1
fi

rg_latest_version="$(release_version_from_tag "$rg_latest_version")"
installed_rg_version=""
if command -v rg >/dev/null 2>&1; then
  installed_rg_version="$(extract_version "$(rg --version 2>/dev/null || true)")"
fi

if [[ -n "$installed_rg_version" ]]; then
  installed_rg_version="$(normalize_version "$installed_rg_version")"
  rg_cmp_result="$(version_cmp "$installed_rg_version" "$rg_latest_version")"
  should_install_rg=true
  if [[ "$rg_cmp_result" -eq 0 ]]; then
    echo "rg ${installed_rg_version} is already the latest version."
    should_install_rg=false
  fi
  if [[ "$rg_cmp_result" -gt 0 ]]; then
    echo "Installed rg (${installed_rg_version}) is newer than latest GitHub release (${rg_latest_version}); skipping install."
    should_install_rg=false
  fi
  if [[ "$should_install_rg" == true ]]; then
    echo "Updating rg from ${installed_rg_version} to ${rg_latest_version}..."
  fi
else
  should_install_rg=true
  echo "rg is not currently installed or version is unreadable; installing latest (${rg_latest_version})..."
fi

if [[ "$should_install_rg" == true ]]; then
  rg_tmp_dir="$(mktemp -d)"

  rg_tarball_path="${rg_tmp_dir}/ripgrep.tar.gz"

  echo "Downloading: $rg_download_url"
  wget -qO "$rg_tarball_path" "$rg_download_url"

  tar -xzf "$rg_tarball_path" -C "$rg_tmp_dir"

  rg_path="$(
    find "$rg_tmp_dir" -type f -name "rg" -perm -u+x \
      | head -n1 || true
  )"
  if [[ -z "$rg_path" ]]; then
    rg_path="$(
      find "$rg_tmp_dir" -type f -name "rg" \
        | head -n1 || true
    )"
  fi

  if [[ -z "$rg_path" ]]; then
    echo "Error: could not find 'rg' binary in extracted ripgrep archive." >&2
    exit 1
  fi

  if [[ -e "$RG_INSTALL_PATH" ]]; then
    rm -f "$RG_INSTALL_PATH"
  fi

  install -o root -g root -m 755 "$rg_path" "$RG_INSTALL_PATH"

  echo "Done. Installed ${RG_INSTALL_PATH} (version ${rg_latest_version})"
fi
