#!/usr/bin/env bash
set -euo pipefail

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
CONFIGS=("$ROOT_DIR/bot-forge.toml" "$ROOT_DIR/catalogs/rust-dev.toml")

violations=0
while IFS=: read -r line text; do
    case "$text" in
        *"http://127.0.0.1"*|*"http://localhost"*) continue ;;
    esac
    printf 'insecure HTTP at bot-forge.toml:%s: %s\n' "$line" "$text" >&2
    violations=$((violations + 1))
done < <(rg -n 'http://' "${CONFIGS[@]}" || true)

while IFS=: read -r line text; do
    printf 'pipe-to-shell at bot-forge.toml:%s: %s\n' "$line" "$text" >&2
    violations=$((violations + 1))
done < <(rg -n 'curl[^|]*\|[[:space:]]*(sh|bash)' "${CONFIGS[@]}" || true)

while IFS=: read -r line text; do
    printf 'private or placeholder endpoint at bot-forge.toml:%s: %s\n' "$line" "$text" >&2
    violations=$((violations + 1))
done < <(rg -ni 'internal-host|example\.(invalid|com)|localhost|127\.0\.0\.1|7\.222\.7\.221' "${CONFIGS[@]}" || true)

while IFS=: read -r line text; do
    printf 'legacy config field at bot-forge.toml:%s: %s\n' "$line" "$text" >&2
    violations=$((violations + 1))
done < <(rg -n 'check_(windows|linux)|install_(windows|linux)|unsupported_platforms|\[\[tools\]\]|= "0"' "${CONFIGS[@]}" || true)

if (( violations > 0 )); then
    printf '%d unsafe default configuration pattern(s) found.\n' "$violations" >&2
    exit 1
fi

printf 'Default configuration download audit passed.\n'
