#!/bin/bash
# BMad6GitHub - Claude Code PreToolUse Hook
# Block access to paths outside current working directory
# Outputs permissionDecision JSON for Claude Code hook system
INPUT=$(cat)

RESULT=$(py -c "
import json, sys, os, re

def normalize(p):
    return os.path.normpath(p).replace(chr(92), '/').lower().rstrip('/')

def is_outside_cwd(path_str, cwd):
    if not path_str or not cwd:
        return False
    n = normalize(path_str)
    c = normalize(cwd)
    if n.startswith('..'):
        return True
    if os.path.isabs(path_str):
        return not n.startswith(c)
    return False

try:
    data = json.load(sys.stdin)
    tool = data.get('tool_name', '')
    ti = data.get('tool_input', {})
    cwd = data.get('cwd', '')
    if not cwd:
        sys.exit(0)

    if tool in ('Read', 'Edit', 'Write', 'Glob', 'Grep'):
        for key in ['file_path', 'path']:
            v = ti.get(key, '')
            if v and is_outside_cwd(v, cwd):
                print('BLOCK')
                sys.exit(0)

    if tool == 'Bash':
        cmd = ti.get('command', '')
        if not cmd:
            sys.exit(0)
        if '..' in cmd:
            print('BLOCK')
            sys.exit(0)
        if '~/' in cmd or '\$HOME' in cmd or '%USERPROFILE%' in cmd:
            print('BLOCK')
            sys.exit(0)
        abs_paths = re.findall(r'(?:/[a-zA-Z][a-zA-Z0-9_/.\-]+|[A-Za-z]:[/\\\\][^\s\"\x27;|&>]+)', cmd)
        for p in abs_paths:
            if is_outside_cwd(p, cwd):
                print('BLOCK')
                sys.exit(0)
except:
    pass
" <<< "$INPUT" 2>/dev/null)

if [ "$RESULT" = "BLOCK" ]; then
  echo '{"permissionDecision":"ask","reason":"WARNING: 현재 작업 디렉토리 외부 경로가 감지되었습니다"}'
  exit 0
fi

exit 0
