#!/usr/bin/env bash
# Aipurity device AI-hygiene scan (macOS / Linux). Read it before running.
# Read-only — it reports, it never deletes.
set -u
echo "== Aipurity device scan =="

echo "-- AI-agent residue --"
for d in "$HOME/.openclaw" "$HOME/.clawdbot" "$HOME/.moltbot" "$HOME/.ollama" \
         "$HOME/.cursor" "$HOME/.continue" \
         "$HOME/Library/Application Support/Claude" \
         "$HOME/Library/Application Support/OpenClaw" \
         "$HOME/.config/Claude"; do
  [ -e "$d" ] && echo "[FOUND] $d"
done

echo "-- Running AI-agent processes --"
ps -A -o comm= 2>/dev/null | grep -iE "openclaw|clawdbot|moltbot|ollama|lm.?studio" | sort -u | sed 's/^/[PROC] /'

echo "-- Listening AI-agent ports --"
for p in 18789 11434 1234; do
  if (command -v lsof >/dev/null && lsof -iTCP:$p -sTCP:LISTEN >/dev/null 2>&1) || nc -z localhost $p 2>/dev/null; then
    echo "[OPEN] localhost:$p"
  fi
done

echo "-- Plaintext secrets in agent dirs --"
# only real config/credential file types; skip .git and sample/template files
for d in "$HOME/.openclaw" "$HOME/.clawdbot" "$HOME/.moltbot"; do
  [ -d "$d" ] || continue
  find "$d" -type f \
    \( -name '*.json' -o -name '*.env' -o -name '.env' -o -name '*.yaml' -o -name '*.yml' \
       -o -name '*.toml' -o -name '*.cfg' -o -name '*.conf' \) \
    -not -path '*/.git/*' -not -name '*.sample' -not -name '*.example' 2>/dev/null |
  while IFS= read -r f; do
    grep -IlE "(api[_-]?key|token|secret|bearer|password)['\"]?[[:space:]]*[:=][[:space:]]*['\"]?[A-Za-z0-9_-]{12,}" "$f" 2>/dev/null |
      sed 's/^/[SECRET?] /'
  done
done

echo "Done. Rotate any flagged credential and delete residue of agents you have uninstalled."
