#!/bin/bash
set -euo pipefail

FAILED=0
echo "=== Release Verification ==="

# Check 1: No real credentials in configs (allow empty strings)
echo "Checking for credentials in configs..."
if grep -r "password:.*[^*\"' ]" configs/ --include="*.yaml" --include="*.yml" 2>/dev/null | grep -v "example\|schema\|changeme\|your_\|\[REDACTED\]\|password: \"\"\|password: ''"; then
    echo "✗ FAIL: Potential passwords found in configs"
    FAILED=1
fi

# Check 2: Config file permissions
echo "Checking config permissions..."
find configs/ -name "*.yaml" ! -name "*example*" ! -name "*schema*" -print0 2>/dev/null | while IFS= read -r -d '' f; do
    PERM=$(stat -c %a "$f" 2>/dev/null || stat -f %A "$f")
    if [ "$PERM" != "600" ]; then
        echo "✗ FAIL: $f has permissions $PERM (expected 600)"
        FAILED=1
    fi
done

# Check 3: No uncommitted changes in configs
echo "Checking for uncommitted config changes..."
if git diff --name-only 2>/dev/null | grep -q "configs/"; then
    echo "WARNING: Uncommitted changes in configs/"
fi

# Check 4: Docker containers stopped
echo "Checking Docker containers..."
if docker ps --filter "name=fetchml" --format "{{.Names}}" 2>/dev/null | grep -q .; then
    echo "WARNING: Running FetchML Docker containers detected"
fi

# Check 5: Podman containers stopped
echo "Checking Podman containers..."
if podman ps --filter "name=fetchml" --format "{{.Names}}" 2>/dev/null | grep -q .; then
    echo "WARNING: Running FetchML Podman containers detected"
fi

# Check 6: No .env files committed
echo "Checking for .env files in git..."
if git ls-files 2>/dev/null | grep -E "^\.env" | grep -v "example"; then
    echo "✗ FAIL: .env files found in git"
    FAILED=1
fi

# Check 7: Binary is not committed
echo "Checking for committed binaries..."
if git ls-files 2>/dev/null | grep -E "^(api-server|worker|bin/)"; then
    echo "✗ FAIL: Binaries found in git"
    FAILED=1
fi

# Check 8: Security audit passes
echo "Running security audit..."
if [ -f ./api-server ]; then
    ./api-server --security-audit 2>&1 | grep -q "All security checks passed" || {
        echo "✗ FAIL: Security audit did not pass"
        FAILED=1
    }
fi

if [ $FAILED -eq 0 ]; then
    echo "All release checks passed"
    exit 0
else
    echo "✗ Release checks failed"
    exit 1
fi
