#!/usr/bin/env sh
set -eu

config_dir="$HOME/.codex"
config_path="$config_dir/config.toml"
auth_path="$config_dir/auth.json"

printf '%s' 'Paste your Grok API key: '
if [ -t 0 ]; then stty -echo; fi
IFS= read -r GROK_API_KEY
if [ -t 0 ]; then stty echo; printf '\n'; fi

if [ -z "${GROK_API_KEY}" ]; then
  printf '%s\n' 'No API key was entered. Configuration was not changed.' >&2
  exit 1
fi

mkdir -p "$config_dir"

if [ -f "$config_path" ] && grep -q '^[[:space:]]*model[[:space:]]*=' "$config_path"; then
  tmp_path="$(mktemp)"
  sed 's/^[[:space:]]*model[[:space:]]*=.*/model = "grok-4.5"/' "$config_path" > "$tmp_path"
  mv "$tmp_path" "$config_path"
elif [ -f "$config_path" ]; then
  tmp_path="$(mktemp)"
  {
    printf '%s\n' 'model = "grok-4.5"'
    cat "$config_path"
  } > "$tmp_path"
  mv "$tmp_path" "$config_path"
else
  printf '%s\n' 'model = "grok-4.5"' > "$config_path"
fi

export GROK_API_KEY
if command -v node >/dev/null 2>&1; then
  node - "$auth_path" <<'NODE'
const fs = require('fs');
const path = process.argv[2];
let auth = {};
if (fs.existsSync(path)) auth = JSON.parse(fs.readFileSync(path, 'utf8'));
auth.OPENAI_API_KEY = process.env.GROK_API_KEY.trim();
fs.writeFileSync(path, `${JSON.stringify(auth, null, 2)}\n`, { mode: 0o600 });
NODE
elif command -v python3 >/dev/null 2>&1; then
  python3 - "$auth_path" <<'PY'
import json, os, sys
path = sys.argv[1]
try:
    with open(path, encoding='utf-8') as source:
        auth = json.load(source)
except FileNotFoundError:
    auth = {}
auth['OPENAI_API_KEY'] = os.environ['GROK_API_KEY'].strip()
with open(path, 'w', encoding='utf-8') as target:
    json.dump(auth, target, indent=2)
    target.write('\n')
os.chmod(path, 0o600)
PY
else
  printf '%s\n' 'Node.js or Python 3 is required to update auth.json.' >&2
  exit 1
fi
unset GROK_API_KEY

printf '%s\n' "Grok 4.5 has been configured: $config_path"
printf '%s\n' 'Confirm that your API key belongs to the Grok group, then restart Codex CLI.'
