#!/usr/bin/env bash
# Access control audit and improvements
# Usage: ./access-control-audit.sh

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SOURCE_PROJECT="/home/intlc/projects/smom-dbis-138"

source "$SOURCE_PROJECT/.env" 2>/dev/null || true

RPC_URL="${RPC_URL_138:-http://192.168.11.250:8545}"
WETH9_BRIDGE="${CCIPWETH9_BRIDGE_CHAIN138:-0x89dd12025bfCD38A168455A44B400e913ED33BE2}"
WETH10_BRIDGE="${CCIPWETH10_BRIDGE_CHAIN138:-0xe0E93247376aa097dB308B92e6Ba36bA015535D0}"

echo "=== Access Control Audit ==="
echo ""

# Check admin roles
check_admin_roles() {
    echo "## Admin Roles"
    echo ""
    
    # Get admin addresses (if contract has owner() function)
    WETH9_ADMIN=$(cast call "$WETH9_BRIDGE" "owner()" --rpc-url "$RPC_URL" 2>/dev/null || echo "N/A")
    WETH10_ADMIN=$(cast call "$WETH10_BRIDGE" "owner()" --rpc-url "$RPC_URL" 2>/dev/null || echo "N/A")
    
    echo "WETH9 Bridge Admin: $WETH9_ADMIN"
    echo "WETH10 Bridge Admin: $WETH10_ADMIN"
    echo ""
    
    # Recommendations
    echo "## Recommendations"
    echo ""
    echo "1. ✅ Use multi-sig wallet for admin operations"
    echo "2. ✅ Implement role-based access control"
    echo "3. ✅ Regular review of admin addresses"
    echo "4. ✅ Use hardware wallets for key management"
    echo "5. ✅ Implement rate limiting on bridge operations"
    echo ""
}

# Check pause functionality
check_pause_functionality() {
    echo "## Pause Functionality"
    echo ""
    
    WETH9_PAUSED=$(cast call "$WETH9_BRIDGE" "paused()" --rpc-url "$RPC_URL" 2>/dev/null || echo "N/A")
    WETH10_PAUSED=$(cast call "$WETH10_BRIDGE" "paused()" --rpc-url "$RPC_URL" 2>/dev/null || echo "N/A")
    
    echo "WETH9 Bridge Paused: $WETH9_PAUSED"
    echo "WETH10 Bridge Paused: $WETH10_PAUSED"
    echo ""
    
    echo "## Emergency Procedures"
    echo ""
    echo "To pause bridge:"
    echo "  cast send $WETH9_BRIDGE 'pause()' --rpc-url $RPC_URL --private-key \$PRIVATE_KEY"
    echo ""
    echo "To unpause bridge:"
    echo "  cast send $WETH9_BRIDGE 'unpause()' --rpc-url $RPC_URL --private-key \$PRIVATE_KEY"
    echo ""
}

# Security recommendations
security_recommendations() {
    echo "## Security Recommendations"
    echo ""
    echo "1. **Multi-Signature Wallet**: Upgrade admin to multi-sig for critical operations"
    echo "2. **Role-Based Access**: Implement granular role-based access control"
    echo "3. **Key Management**: Use hardware wallets or secure key management systems"
    echo "4. **Rate Limiting**: Implement rate limiting on bridge operations"
    echo "5. **Monitoring**: Set up alerts for admin operations"
    echo "6. **Audit Trail**: Maintain comprehensive audit logs"
    echo "7. **Regular Reviews**: Conduct regular access control reviews"
    echo ""
}

check_admin_roles
check_pause_functionality
security_recommendations

