#!/usr/bin/env bash
# macOS/Linux; preview by default. No history deletion or automatic login.
set -euo pipefail
if [[ ${1:-} != '' && ${1:-} != '--execute' ]]; then
  echo 'Usage: bash cc-preserve-history.sh [--execute]' >&2; exit 2
fi
command -v python3 >/dev/null
command -v claude >/dev/null
if [[ -n ${CLAUDE_CONFIG_DIR:-} ]]; then
  echo 'Custom CLAUDE_CONFIG_DIR detected. Review its paths manually; no changes made.' >&2
  exit 2
fi
python3 - "${1:-}" <<'PY'
import json, os, pathlib, shutil, subprocess, sys, tempfile
home = pathlib.Path.home()
root = home / '.claude'
meta = home / '.claude.json'
if root.is_symlink() or meta.is_symlink():
    raise SystemExit('Symlinked Claude roots require manual review; no changes made.')
selected = [root / n for n in ('projects', 'history.jsonl', 'file-history', 'CLAUDE.md')]
selected = [p for p in selected if p.exists()]
print('Preserve and privately back up: projects, history.jsonl, file-history, CLAUDE.md when present.')
print('Back up .claude.json privately, invoke official auth logout, remove residual oauthAccount metadata.')
print('No session history, memory, settings, skills or device identifiers will be deleted.')
print('Backups and transcripts may contain account details or secrets. Do not share them.')
if sys.argv[1] != '--execute':
    print('Preview only. Stop all running CC sessions before using --execute.')
    raise SystemExit(0)
os.umask(0o077)
backup_root = home / '.cc-history-backups'
if backup_root.is_symlink():
    raise SystemExit('Refusing symlinked backup directory.')
backup_root.mkdir(mode=0o700, exist_ok=True)
backup_root.chmod(0o700)
backup = pathlib.Path(tempfile.mkdtemp(prefix='history-', dir=backup_root))
for p in selected:
    if p.is_dir():
        shutil.copytree(p, backup / p.name, symlinks=True)
    else:
        shutil.copy2(p, backup / p.name, follow_symlinks=False)
if meta.exists():
    shutil.copy2(meta, backup / 'claude-global.private.json')
# Use the CLI's credential provider; do not guess Keychain service names.
result = subprocess.run(['claude', 'auth', 'logout'], capture_output=True)
if result.returncode:
    raise SystemExit('Logout failed; backup retained. Check claude auth logout locally. No manual cleanup performed.')
if meta.exists():
    data = json.loads(meta.read_text())
    if 'oauthAccount' in data:
        del data['oauthAccount']
        fd, tmp = tempfile.mkstemp(prefix='.claude-meta-', dir=home)
        try:
            with os.fdopen(fd, 'w') as f:
                json.dump(data, f, ensure_ascii=False, indent=2)
                f.write('\n')
            os.replace(tmp, meta)
        finally:
            if os.path.exists(tmp): os.unlink(tmp)
print('Done. Local work history retained; private backup:', backup)
print('Review API keys, OAuth-token environment variables and apiKeyHelper separately.')
print('This is not a scrubber for secrets embedded in transcripts or a server-side account reset.')
PY
