#!/usr/bin/env bash
set -euo pipefail

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
SEARCH_ROOTS=(
  "$ROOT_DIR/src"
  "$ROOT_DIR/tests"
  "$ROOT_DIR/tools"
  "$ROOT_DIR/scripts"
)
URL_SEARCH_ROOTS=(
  "$ROOT_DIR/src"
  "$ROOT_DIR/tools"
  "$ROOT_DIR/scripts"
)
RG_COMMON=(--glob '!verify-safety.sh' --glob '!**/bin/**' --glob '!**/obj/**')

DISALLOWED_PATTERN='SetClipboard|OpenClipboard|GetClipboardData|AddClipboardFormatListener|UpdateResource|BeginUpdateResource|EndUpdateResource|SHGetSpecialFolderPath|CreateMutex|WindowsUpdate|zip_work|TARGET_PATH|--merge-env|CryptUnprotectData|Login Data|wallet\.dat'

if rg "${RG_COMMON[@]}" -n "$DISALLOWED_PATTERN" "${SEARCH_ROOTS[@]}"; then
  echo "error: disallowed malware-adjacent capability found" >&2
  exit 1
fi

URL_PATTERN='https?://[^"[:space:]]+'
if rg "${RG_COMMON[@]}" --glob '!*.axaml' -n "$URL_PATTERN" "${URL_SEARCH_ROOTS[@]}" \
  | rg -v 'http://(127\.0\.0\.1|localhost)(:[0-9]+)?(/[^"[:space:]]*)?' \
  | rg -v 'http://\{'; then
  echo "error: non-loopback URL literal found" >&2
  exit 1
fi

echo "Safety scan passed."
