#!/usr/bin/env bash
# Hermes pre_tool_call hook: block raw scp/rsync/sftp/ssh transfers to the
# configured shared-folder host unless accessSharedFolder.sh is used.
#
# Reads JSON from stdin; prints block JSON to stdout when matched.
# Env: SHARED_FOLDER_REMOTE_HOST, SHARED_FOLDER_REMOTE_BASE, HERMES_WORKER_DIR

set -euo pipefail

REMOTE_HOST="${SHARED_FOLDER_REMOTE_HOST:-root@kobald.com}"
REMOTE_BASE="${SHARED_FOLDER_REMOTE_BASE:-/mnt/HC_Volume_105777295/hermes-agent}"

payload="$(cat)"
tool_name="$(printf '%s' "$payload" | python3 -c "import json,sys; d=json.load(sys.stdin); print(d.get('tool_name') or '')" 2>/dev/null || echo "")"

if [[ "$tool_name" != "terminal" ]]; then
  exit 0
fi

command="$(printf '%s' "$payload" | python3 -c "import json,sys; d=json.load(sys.stdin); ti=d.get('tool_input') or {}; print(ti.get('command') or '')" 2>/dev/null || echo "")"

[[ -n "$command" ]] || exit 0

# Allowed when using the blessed wrapper
if [[ "$command" == *accessSharedFolder.sh* ]]; then
  exit 0
fi

host_pattern="${REMOTE_HOST#*@}"
host_user="${REMOTE_HOST%@*}"

block=0

# Transfer commands targeting the shared host or volume path
if printf '%s' "$command" | grep -qE '\b(scp|rsync|sftp)\b'; then
  if printf '%s' "$command" | grep -qF "$host_pattern" \
     || printf '%s' "$command" | grep -qF "$REMOTE_BASE"; then
    block=1
  fi
fi

if printf '%s' "$command" | grep -qE '\bssh\b'; then
  if printf '%s' "$command" | grep -qE "(scp|rsync|cat>|tee|cp |mv )" \
     && { printf '%s' "$command" | grep -qF "$host_pattern" \
          || printf '%s' "$command" | grep -qF "$REMOTE_BASE"; }; then
    block=1
  fi
fi

if [[ "$block" -eq 1 ]]; then
  worker_dir="${HERMES_WORKER_DIR:-hermes-worker}"
  printf '{"action":"block","message":"Use %s/tools/accessSharedFolder.sh get|put|ls for shared-volume transfers instead of raw scp/rsync to %s."}\n' \
    "$worker_dir" "$REMOTE_HOST"
fi

exit 0
