#!/usr/bin/env bash
# opencode-team-config installer (macOS + Linux, no Node/Homebrew required)
#
# Mirrors the conventions of the real OpenCode installer
# (https://opencode.ai/install): a single script, a --version pin,
# idempotent shell-profile wiring, and a local-file override for
# offline/testing use instead of a network fetch.
#
set -euo pipefail

# Distribution base URL. Override via OCT_BASE_URL (e.g. a local mirror or a
# different host); defaults to the self-hosted static host. Distribution no
# longer depends on GitHub auth or the GitHub Releases API.
BASE_URL="${OCT_BASE_URL:-https://llm-gateway.envision-tech.co.ke/downloads/opencode-team-config}"

MARK_BEGIN="# >>> opencode-team-config managed block (do not edit by hand) >>>"
MARK_END="# <<< opencode-team-config managed block <<<"

# Versioned install root, same "keep every version, symlink the current one"
# pattern as Homebrew's Cellar+opt convention -- solved here by hand since
# there is no package manager to do it for us. This is deliberate: it is
# what avoids the "unstable path baked into the rc file" trap found (and
# fixed) while building the Homebrew formula for this same package.
INSTALL_ROOT="${OPENCODE_TEAM_CONFIG_HOME:-$HOME/.opencode-team-config}"
CURRENT_LINK="$INSTALL_ROOT/current"

# Gateway key is stored OUTSIDE the shell rc file, in a 0600 file, so it is
# never written into a world/group-readable profile. The managed block below
# only *sources* that file when it exists.
ENV_DIR="$HOME/.config/envision"
ENV_FILE="$ENV_DIR/gateway.env"
gateway_source_line='[ -f "$HOME/.config/envision/gateway.env" ] && . "$HOME/.config/envision/gateway.env"'

# A standalone `export ENVISION_GATEWAY_KEY=...` assignment. Matches the
# variable name only (single/double-quoted or bare value, leading whitespace,
# optional trailing comment); the key value itself is never captured or
# printed.
legacy_key_re="^[[:space:]]*export[[:space:]]+ENVISION_GATEWAY_KEY[[:space:]]*=[[:space:]]*('[^']*'|\"[^\"]*\"|[^[:space:]'\"]+)[[:space:]]*(#.*)?\$"

usage() {
  cat <<EOF
opencode-team-config installer

Usage: install.sh [options]

Options:
  -h, --help              Show this help
  -v, --version <version> Install a specific version (default: latest release)
      --file <path>       Install from a local tarball instead of downloading
                           (offline use / testing; skips network + checksum)
      --doctor            Check current install status and merged OpenCode config
      --uninstall          Remove the managed shell-profile block (keeps
                           downloaded versions on disk; remove $INSTALL_ROOT
                           yourself if you want to reclaim the space); also
                           removes the gateway env file unless --keep-key
      --gateway-key <sk-...>
                           Also store the Envision gateway key (exported as
                           ENVISION_GATEWAY_KEY) in $ENV_FILE (mode 0600) and
                           source it from your shell rc. Must start with 'sk-'.
                           To rotate the key later, use: opencode-team-config set-key
      --keep-key           With --uninstall, keep the gateway env file on disk
      --no-modify-profile  Don't edit shell rc files; print the export line
                           instead

Examples:
  curl -fsSL https://llm-gateway.envision-tech.co.ke/downloads/opencode-team-config/install.sh | bash
  curl -fsSL https://llm-gateway.envision-tech.co.ke/downloads/opencode-team-config/install.sh | bash -s -- --version 1.0.0
  ./install.sh --file ./opencode-team-config-1.0.0.tar.gz --gateway-key sk-your-gateway-key
  ./install.sh --doctor
  ./install.sh --uninstall
EOF
}

version=""
local_file=""
do_uninstall=false
do_doctor=false
no_modify_profile=false
gateway_key=""
keep_key=false

while [[ $# -gt 0 ]]; do
  case "$1" in
    -h|--help) usage; exit 0 ;;
    -v|--version)
      [[ -n "${2:-}" ]] || { echo "Error: --version requires an argument" >&2; exit 1; }
      version="$2"; shift 2 ;;
    --file)
      [[ -n "${2:-}" ]] || { echo "Error: --file requires a path" >&2; exit 1; }
      local_file="$2"; shift 2 ;;
    --uninstall) do_uninstall=true; shift ;;
    --doctor) do_doctor=true; shift ;;
    --gateway-key)
      [[ -n "${2:-}" ]] || { echo "Error: --gateway-key requires an argument" >&2; exit 1; }
      gateway_key="$2"; shift 2 ;;
    --keep-key) keep_key=true; shift ;;
    --no-modify-profile) no_modify_profile=true; shift ;;
    *) echo "Warning: unknown option '$1'" >&2; shift ;;
  esac
done

# Validate the gateway key without ever logging it.
if [ -n "$gateway_key" ]; then
  case "$gateway_key" in
    sk-*) ;;
    *) echo "Error: --gateway-key must start with 'sk-'" >&2; exit 1 ;;
  esac
  case "$gateway_key" in
    *"'"*) echo "Error: --gateway-key must not contain a single quote (')" >&2; exit 1 ;;
  esac
fi

sha256_of() {
  if command -v shasum >/dev/null 2>&1; then
    shasum -a 256 "$1" | awk '{print $1}'
  elif command -v sha256sum >/dev/null 2>&1; then
    sha256sum "$1" | awk '{print $1}'
  else
    echo ""
  fi
}

rc_file() {
  local current_shell
  current_shell=$(basename "${SHELL:-/bin/zsh}")
  case "$current_shell" in
    zsh) echo "${ZDOTDIR:-$HOME}/.zshrc" ;;
    bash)
      if [ -f "$HOME/.bash_profile" ]; then echo "$HOME/.bash_profile"
      else echo "$HOME/.bashrc"; fi ;;
    *) echo "$HOME/.zshrc" ;;
  esac
}

block_text() {
  printf '%s\nexport OPENCODE_CONFIG_DIR="%s/config-dir"\n' \
    "$MARK_BEGIN" "$CURRENT_LINK"
  if [ -n "$gateway_key" ]; then
    printf '%s\n' "$gateway_source_line"
  fi
  printf '%s\n' "$MARK_END"
}

write_gateway_env() {
  mkdir -p "$ENV_DIR"
  chmod 700 "$ENV_DIR"
  ( umask 077; printf "export ENVISION_GATEWAY_KEY='%s'\n" "$gateway_key" > "$ENV_FILE" )
  chmod 600 "$ENV_FILE"
  echo "Stored gateway key in $ENV_FILE (mode 600)."
  echo "To rotate the key later (instead of hand-editing this file): opencode-team-config set-key"
}

cmd_uninstall() {
  local file; file=$(rc_file)
  if [ -f "$file" ] && grep -qF "$MARK_BEGIN" "$file"; then
    local tmp; tmp=$(mktemp)
    awk -v b="$MARK_BEGIN" -v e="$MARK_END" '
      $0==b {skip=1}
      !skip {print}
      $0==e {skip=0}
    ' "$file" > "$tmp"
    mv "$tmp" "$file"
    echo "Removed managed block from $file."
  else
    echo "No managed block found in $file."
  fi

  if [ "$keep_key" = true ]; then
    echo "Keeping gateway env file ($ENV_FILE) due to --keep-key."
  elif [ -f "$ENV_FILE" ]; then
    rm -f "$ENV_FILE"
    echo "Removed $ENV_FILE."
    rmdir "$ENV_DIR" 2>/dev/null || true
  fi

  echo "Downloaded versions remain under $INSTALL_ROOT. Delete that directory to fully remove."
}

cmd_doctor() {
  echo "opencode-team-config installer status"
  echo "  install root: $INSTALL_ROOT"
  if [ -L "$CURRENT_LINK" ]; then
    local target; target=$(readlink "$CURRENT_LINK")
    echo "  current -> $target"
    if [ -f "$CURRENT_LINK/config-dir/.version" ]; then
      echo "  installed version: $(cat "$CURRENT_LINK/config-dir/.version")"
    fi
  else
    echo "  not installed (no $CURRENT_LINK symlink)"
  fi

  local envdir="${OPENCODE_CONFIG_DIR:-}"
  if [ -z "$envdir" ]; then
    echo "  OPENCODE_CONFIG_DIR is NOT set in this shell. Open a new shell after installing, or source your rc file."
  else
    echo "  OPENCODE_CONFIG_DIR=$envdir"
  fi

  # Gateway key status -- never print the key itself.
  if [ -n "${ENVISION_GATEWAY_KEY:-}" ]; then
    echo "  ENVISION_GATEWAY_KEY is set in this shell."
  else
    echo "  ENVISION_GATEWAY_KEY is NOT set in this shell."
  fi
  if [ -f "$ENV_FILE" ]; then
    echo "  gateway env file present: $ENV_FILE"
  else
    echo "  gateway env file absent: $ENV_FILE"
  fi
  if [ -n "${ENVISION_GATEWAY_KEY:-}" ]; then
    local code
    code=$(curl -fsS -o /dev/null -w '%{http_code}' "https://llm-gateway.envision-tech.co.ke/v1/models" -H "Authorization: Bearer $ENVISION_GATEWAY_KEY" 2>/dev/null || true)
    if [ -z "$code" ]; then
      echo "  gateway key check: request failed (network or invalid endpoint); non-fatal"
    else
      case "$code" in
        200) echo "  gateway key check: HTTP 200 (OK)" ;;
        401) echo "  gateway key check: HTTP 401 (invalid key)" ;;
        *)   echo "  gateway key check: HTTP $code" ;;
      esac
    fi
  fi

  if ! command -v opencode >/dev/null 2>&1; then
    echo "  'opencode' not found on PATH; cannot check merged config."
    return 1
  fi

  echo ""
  echo "Checking merged OpenCode config (opencode debug config)..."
  local out
  if ! out=$(opencode debug config 2>&1); then
    echo "  'opencode debug config' failed:"
    echo "$out"
    return 1
  fi
  # Heuristic substring check, not full JSON parsing -- deliberate,
  # dependency-free tradeoff (no guaranteed jq/python/node on a bare
  # curl|bash install). The npm package's `doctor` command does a real
  # JSON parse and is the more rigorous check where Node is available.
  local ok=true
  for agent in router builder fixer architect; do
    if echo "$out" | grep -q "\"$agent\":"; then
      echo "  agent \"$agent\": present (heuristic match)"
    else
      echo "  agent \"$agent\": MISSING"
      ok=false
    fi
  done
  if [ "$ok" = true ]; then
    echo ""
    echo "All four agent names found in the merged config (heuristic check)."
  else
    echo ""
    echo "One or more expected agent names were not found."
    return 1
  fi
}

# --- legacy `export ENVISION_GATEWAY_KEY=...` cleanup ---
# Before this installer existed, many users pasted a manual
# `export ENVISION_GATEWAY_KEY=...` line straight into their shell rc. Now that
# the key lives in $ENV_FILE (mode 0600) and is sourced by the managed block,
# that manual line is redundant AND keeps the secret in a world/group-readable
# profile. Remove such stray lines -- but ONLY when this installer actually
# manages the key (just stored one, or $ENV_FILE exists and the managed block
# sources it), so we never delete a user's only key source. Lines inside the
# managed block are never touched.
cleanup_legacy_exports() {
  local managing=false
  if [ -n "$gateway_key" ]; then
    managing=true
  elif [ -f "$ENV_FILE" ]; then
    local rf; rf=$(rc_file)
    if [ -f "$rf" ] && grep -qF "$gateway_source_line" "$rf"; then
      managing=true
    fi
  fi
  [ "$managing" = true ] || return 0

  local ts f
  ts=$(date +%Y%m%d-%H%M%S)
  for f in "$HOME/.zshrc" "$HOME/.zprofile" "$HOME/.bashrc" "$HOME/.bash_profile" "$HOME/.profile"; do
    [ -f "$f" ] || continue
    local n tmp backup
    n=$(awk -v b="$MARK_BEGIN" -v e="$MARK_END" -v re="$legacy_key_re" '
      $0==b {inb=1; next}
      $0==e {inb=0; next}
      inb {next}
      $0 ~ re {n++}
      {next}
      END {print n+0}
    ' "$f")
    [ "$n" -gt 0 ] || continue

    tmp=$(mktemp)
    awk -v b="$MARK_BEGIN" -v e="$MARK_END" -v re="$legacy_key_re" '
      $0==b {inb=1; print; next}
      $0==e {inb=0; print; next}
      inb {print; next}
      $0 ~ re {next}
      {print}
    ' "$f" > "$tmp"
    backup="$f.bak-$ts"
    cp -p "$f" "$backup"
    # The backup contains the secret (the rc file being edited), so restrict it
    # to the owner rather than inheriting the rc file's world-readable mode.
    chmod 600 "$backup"
    cat "$tmp" > "$f"
    rm -f "$tmp"
    echo "Removed $n redundant 'export ENVISION_GATEWAY_KEY' line(s) from $f (backup: $backup)."
  done
}

if [ "$do_uninstall" = true ]; then cmd_uninstall; exit $?; fi
if [ "$do_doctor" = true ]; then cmd_doctor; exit $?; fi

# --- resolve the archive to install ---
tmp_dir=$(mktemp -d)
trap 'rm -rf "$tmp_dir"' EXIT

if [ -n "$local_file" ]; then
  [ -f "$local_file" ] || { echo "Error: file not found: $local_file" >&2; exit 1; }
  archive="$local_file"
  resolved_version="${version:-local}"
  echo "Installing from local file: $local_file"
else
  if [ -z "$version" ]; then
    resolved_version=$(curl -fsSL "$BASE_URL/latest.txt" | tr -d '[:space:]')
    [ -n "$resolved_version" ] || { echo "Error: failed to resolve latest version" >&2; exit 1; }
  else
    resolved_version="${version#v}"
  fi

  asset="opencode-team-config-${resolved_version}.tar.gz"
  url="$BASE_URL/$asset"
  archive="$tmp_dir/$asset"
  echo "Downloading $url"
  if ! curl -fsSL -o "$archive" "$url"; then
    echo "Error: failed to download $url" >&2
    exit 1
  fi

  if curl -fsSL -o "$archive.sha256" "$url.sha256" 2>/dev/null; then
    expected=$(awk '{print $1}' "$archive.sha256")
    actual=$(sha256_of "$archive")
    if [ -z "$actual" ]; then
      echo "Warning: no shasum/sha256sum available, skipping checksum verification" >&2
    elif [ "$expected" != "$actual" ]; then
      echo "Error: checksum mismatch for $asset" >&2
      echo "  expected: $expected" >&2
      echo "  actual:   $actual" >&2
      exit 1
    else
      echo "Checksum verified."
    fi
  else
    echo "Warning: no .sha256 file published for this release, skipping checksum verification" >&2
  fi
fi

# --- install into a versioned directory, then atomically repoint 'current' ---
version_dir="$INSTALL_ROOT/versions/$resolved_version"
mkdir -p "$version_dir"
tar -xzf "$archive" -C "$version_dir"

if [ ! -d "$version_dir/config-dir" ]; then
  echo "Error: archive did not contain a config-dir/ directory" >&2
  exit 1
fi

mkdir -p "$INSTALL_ROOT"
ln -sfn "$version_dir" "$CURRENT_LINK"
echo "Installed version $resolved_version -> $CURRENT_LINK"

# --- optionally store the gateway key outside the rc file ---
if [ -n "$gateway_key" ]; then
  write_gateway_env
fi

# --- wire OPENCODE_CONFIG_DIR into the shell profile, idempotently ---
if [ "$no_modify_profile" = true ]; then
  echo "Skipping shell profile edit (--no-modify-profile). Export manually:"
  echo "  export OPENCODE_CONFIG_DIR=\"$CURRENT_LINK/config-dir\""
  if [ -n "$gateway_key" ]; then
    echo "  . \"$ENV_FILE\""
  fi
else
  file=$(rc_file)
  if [ -f "$file" ] && grep -qF "$MARK_BEGIN" "$file"; then
    if [ -n "$gateway_key" ] && ! grep -qF "$gateway_source_line" "$file"; then
      rc_tmp=$(mktemp)
      awk -v e="$MARK_END" -v line="$gateway_source_line" '
        $0==e {print line}
        {print}
      ' "$file" > "$rc_tmp"
      mv "$rc_tmp" "$file"
      echo "Added gateway source line to managed block in $file."
    else
      echo "Managed block already present in $file (idempotent, no changes)."
    fi
  else
    { [ -f "$file" ] && [ -s "$file" ] && echo ""; block_text; } >> "$file" 2>/dev/null || {
      mkdir -p "$(dirname "$file")"
      block_text >> "$file"
    }
    echo "Added managed block to $file:"
    block_text
    echo "Open a new shell, then run: opencode debug config"
  fi
fi

# Remove any stray manual `export ENVISION_GATEWAY_KEY=...` now that the key is
# managed. Skipped under --no-modify-profile, which promises not to touch rc
# files at all.
if [ "$no_modify_profile" = false ]; then
  cleanup_legacy_exports
fi

echo ""
echo "Verify with:"
echo "  $0 --doctor"
