#!/bin/sh
# OpenUncensored setup: connects Claude Code, Codex and OpenCode on this machine to OpenUncensored.
#
#   curl -fsSL https://openuncensored.com/setup.sh | sh
#
# It asks before each change, keeps a backup of every config file it edits, and never changes how your
# tools run by default: it adds separate commands (claude-uncensored, codex-uncensored, opencode-uncensored).
#
#   ~/.config/openuncensored/key       your key, readable only by you
#   ~/.local/bin/claude-uncensored     Claude Code on OpenUncensored (environment variables only)
#   ~/.codex/config.toml               adds an "openuncensored" provider and an "uncensored" profile
#   ~/.local/bin/codex-uncensored      Codex with that profile
#   ~/.config/opencode/opencode.json   adds an "openuncensored" provider
#   ~/.local/bin/opencode-uncensored   OpenCode with your key set
#
# Options (environment variables): OPENUNCENSORED_API_KEY=ou-... to skip the prompt, OU_MODEL=<model id> to pick
# the default model, OU_SETUP_YES=1 to answer yes to every question. Models: https://openuncensored.com/models
set -eu

API="https://api.openuncensored.com/v1"
ANTHROPIC="https://api.openuncensored.com"
MODEL="${OU_MODEL:-deepseek-v4.1-flash-1017-uncensored}"
EXTRA_MODELS="kimi-k3.1-pro-uncensored glm-5.3-flash-uncensored"
DIR="$HOME/.config/openuncensored"
BIN="$HOME/.local/bin"
STAMP=$(date +%Y%m%d%H%M%S)

say() { printf '%s\n' "$*"; }
have() { command -v "$1" >/dev/null 2>&1; }
# ask "question" default(y|n): returns 0 for yes
ask() {
  if [ "${OU_SETUP_YES:-}" = "1" ]; then return 0; fi
  if ! [ -r /dev/tty ]; then [ "$2" = "y" ]; return; fi
  if [ "$2" = "y" ]; then hint="[Y/n]"; else hint="[y/N]"; fi
  printf '%s %s ' "$1" "$hint" > /dev/tty
  read -r reply < /dev/tty || reply=""
  case "$reply" in
    y|Y|yes|Yes) return 0 ;;
    n|N|no|No) return 1 ;;
    *) [ "$2" = "y" ] ;;
  esac
}
backup() {
  if [ -f "$1" ]; then cp "$1" "$1.bak.$STAMP" && say "  Backup: $1.bak.$STAMP"; fi
}

have curl || { say "curl is required."; exit 1; }

# ---- the key
KEY="${OPENUNCENSORED_API_KEY:-${OU_API_KEY:-}}"
if [ -z "$KEY" ] && [ -f "$DIR/key" ]; then KEY=$(cat "$DIR/key"); fi
if [ -z "$KEY" ]; then
  if ! [ -r /dev/tty ]; then say "No terminal to ask for the key. Run again with OPENUNCENSORED_API_KEY=ou-..."; exit 1; fi
  say "Paste your OpenUncensored key (it starts with ou-). No key yet? Get one at https://openuncensored.com/credits"
  printf 'Key: ' > /dev/tty
  stty -echo < /dev/tty 2>/dev/null || true
  read -r KEY < /dev/tty || KEY=""
  stty echo < /dev/tty 2>/dev/null || true
  printf '\n' > /dev/tty
fi
case "$KEY" in
  ou-*) ;;
  *) say "That does not look like an OpenUncensored key (they start with ou-)."; exit 1 ;;
esac
status=$(curl -s -o /dev/null -w '%{http_code}' -H "Authorization: Bearer $KEY" "$API/credits" || true)
case "$status" in
  401) say "The key was not accepted. Check it on https://openuncensored.com/credits"; exit 1 ;;
  000|"") say "Could not reach $API. Check your connection and try again."; exit 1 ;;
esac
mkdir -p "$DIR" "$BIN"
old_umask=$(umask); umask 077
printf '%s\n' "$KEY" > "$DIR/key"
umask "$old_umask"
chmod 600 "$DIR/key"
say "Key saved to $DIR/key (readable only by you)."
say ""

made=""

# ---- Claude Code: a wrapper that sets the Anthropic variables, nothing global
if have claude; then
  if ask "Set up Claude Code? (adds the command claude-uncensored)" y; then
    cat > "$BIN/claude-uncensored" <<EOF
#!/bin/sh
# Claude Code on OpenUncensored. Written by https://openuncensored.com/setup.sh
export ANTHROPIC_BASE_URL="$ANTHROPIC"
export ANTHROPIC_API_KEY="\$(cat "$DIR/key")"
export ANTHROPIC_MODEL="\${OU_MODEL:-$MODEL}"
export ANTHROPIC_DEFAULT_OPUS_MODEL="\$ANTHROPIC_MODEL"
export ANTHROPIC_DEFAULT_SONNET_MODEL="\$ANTHROPIC_MODEL"
export ANTHROPIC_DEFAULT_HAIKU_MODEL="\$ANTHROPIC_MODEL"
export CLAUDE_CODE_SUBAGENT_MODEL="\$ANTHROPIC_MODEL"
exec claude "\$@"
EOF
    chmod +x "$BIN/claude-uncensored"
    made="$made claude-uncensored"
    say "  Claude Code: run claude-uncensored (OU_MODEL=<id> claude-uncensored to pick another model)."
  fi
fi

# ---- Codex: a provider and a profile in config.toml, plus a wrapper that sets the key
if have codex; then
  if ask "Set up Codex? (adds a provider and profile to ~/.codex/config.toml, and the command codex-uncensored)" y; then
    CFG="$HOME/.codex/config.toml"
    mkdir -p "$HOME/.codex"
    if [ -f "$CFG" ] && grep -q '^\[model_providers\.openuncensored\]' "$CFG"; then
      say "  Codex already has an openuncensored provider: left as it is."
    else
      backup "$CFG"
      {
        printf '\n[model_providers.openuncensored]\nname = "OpenUncensored"\nbase_url = "%s"\nenv_key = "OU_API_KEY"\nwire_api = "responses"\n' "$API"
        if ! { [ -f "$CFG" ] && grep -q '^\[profiles\.uncensored\]' "$CFG"; }; then
          printf '\n[profiles.uncensored]\nmodel_provider = "openuncensored"\nmodel = "%s"\n' "$MODEL"
        fi
      } >> "$CFG"
      say "  Added the openuncensored provider and the uncensored profile to $CFG"
    fi
    cat > "$BIN/codex-uncensored" <<EOF
#!/bin/sh
# Codex on OpenUncensored. Written by https://openuncensored.com/setup.sh
export OU_API_KEY="\$(cat "$DIR/key")"
exec codex --profile uncensored "\$@"
EOF
    chmod +x "$BIN/codex-uncensored"
    made="$made codex-uncensored"
    say "  Codex: run codex-uncensored."
  fi
fi

# ---- OpenCode: a provider in opencode.json (format by major version), plus a wrapper that sets the key
if have opencode; then
  if ask "Set up OpenCode? (adds a provider to ~/.config/opencode/opencode.json, and the command opencode-uncensored)" y; then
    CFG="$HOME/.config/opencode/opencode.json"
    major=$(opencode --version 2>/dev/null | sed -n 's/^[^0-9]*\([0-9][0-9]*\)\..*/\1/p' | head -n 1)
    [ -n "$major" ] || major=1
    mkdir -p "$HOME/.config/opencode"
    if [ -f "$HOME/.config/opencode/opencode.jsonc" ] && ! [ -f "$CFG" ]; then
      say "  Your OpenCode config is opencode.jsonc (with comments), which this script does not edit."
      say "  Add the provider by hand: https://openuncensored.com/opencode-uncensored-provider"
    else
      backup "$CFG"
      merged=0
      if have python3; then
        if python3 - "$CFG" "$major" "$API" "$MODEL $EXTRA_MODELS" <<'PY'
import json, os, sys
path, major, api, models = sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4].split()
cfg = {"$schema": "https://opencode.ai/config.json"}
if os.path.exists(path) and os.path.getsize(path) > 0:
    with open(path) as f:
        cfg = json.load(f)
entries = {m: {"name": m} for m in models}
if major == "2":
    cfg.setdefault("providers", {})["openuncensored"] = {
        "name": "OpenUncensored", "env": ["OPENUNCENSORED_API_KEY"],
        "package": "@opencode/ai/providers/openai-compatible", "settings": {"baseURL": api}, "models": entries}
else:
    cfg.setdefault("provider", {})["openuncensored"] = {
        "npm": "@ai-sdk/openai-compatible", "name": "OpenUncensored",
        "options": {"baseURL": api, "apiKey": "{env:OPENUNCENSORED_API_KEY}"}, "models": entries}
with open(path, "w") as f:
    json.dump(cfg, f, indent=2)
    f.write("\n")
PY
        then merged=1; fi
      elif have node; then
        if node -e '
const fs = require("fs");
const [path, major, api, models] = process.argv.slice(1);
let cfg = { $schema: "https://opencode.ai/config.json" };
if (fs.existsSync(path) && fs.statSync(path).size > 0) cfg = JSON.parse(fs.readFileSync(path, "utf8"));
const entries = Object.fromEntries(models.split(" ").map((m) => [m, { name: m }]));
if (major === "2") {
  cfg.providers = cfg.providers || {};
  cfg.providers.openuncensored = { name: "OpenUncensored", env: ["OPENUNCENSORED_API_KEY"], package: "@opencode/ai/providers/openai-compatible", settings: { baseURL: api }, models: entries };
} else {
  cfg.provider = cfg.provider || {};
  cfg.provider.openuncensored = { npm: "@ai-sdk/openai-compatible", name: "OpenUncensored", options: { baseURL: api, apiKey: "{env:OPENUNCENSORED_API_KEY}" }, models: entries };
}
fs.writeFileSync(path, JSON.stringify(cfg, null, 2) + "\n");
' "$CFG" "$major" "$API" "$MODEL $EXTRA_MODELS"; then merged=1; fi
      fi
      if [ "$merged" = "1" ]; then
        say "  Added the openuncensored provider to $CFG (OpenCode $major format)."
      else
        say "  Could not edit $CFG automatically (no python3 or node, or the file is not plain JSON)."
        say "  Add the provider by hand: https://openuncensored.com/opencode-uncensored-provider"
      fi
    fi
    cat > "$BIN/opencode-uncensored" <<EOF
#!/bin/sh
# OpenCode with your OpenUncensored key set. Written by https://openuncensored.com/setup.sh
export OPENUNCENSORED_API_KEY="\$(cat "$DIR/key")"
exec opencode "\$@"
EOF
    chmod +x "$BIN/opencode-uncensored"
    made="$made opencode-uncensored"
    say "  OpenCode: run opencode-uncensored and pick openuncensored/$MODEL (or: opencode-uncensored run -m openuncensored/$MODEL \"...\")."
  fi
fi

say ""
if [ -z "$made" ]; then
  say "None of Claude Code, Codex or OpenCode was found (or you skipped them). Your key is saved in $DIR/key."
  say "Setup for other tools: https://openuncensored.com/docs#integrations"
  exit 0
fi

# ---- optional: the key in the shell profile, so plain opencode and codex --profile uncensored work too
case "${SHELL:-}" in
  */zsh) RC="$HOME/.zshrc" ;;
  */bash) RC="$HOME/.bashrc" ;;
  *) RC="$HOME/.profile" ;;
esac
if ! grep -q 'openuncensored/key' "$RC" 2>/dev/null; then
  if ask "Also load the key in $RC, so plain opencode and codex --profile uncensored find it?" n; then
    printf '\n# OpenUncensored key (https://openuncensored.com/setup.sh)\nexport OPENUNCENSORED_API_KEY="$(cat "$HOME/.config/openuncensored/key" 2>/dev/null)"\nexport OU_API_KEY="$OPENUNCENSORED_API_KEY"\n' >> "$RC"
    say "  Added to $RC (open a new terminal to use it)."
  fi
fi

case ":$PATH:" in
  *":$BIN:"*) ;;
  *) say ""; say "Note: $BIN is not on your PATH. Add it with:"; say "  echo 'export PATH=\"\$HOME/.local/bin:\$PATH\"' >> $RC && exec \$SHELL" ;;
esac
say ""
say "Done. New commands:$made"
say "Every model id: curl -s $API/models"
