#!/usr/bin/env bash
# Dependency management and updates
# Usage: ./dependency-management.sh [check|update|audit]

set -euo pipefail

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

ACTION="${1:-check}"

# Check dependencies
check_dependencies() {
    echo "=== Dependency Check ==="
    echo ""
    
    # Check Foundry
    if command -v forge >/dev/null 2>&1; then
        FORGE_VERSION=$(forge --version 2>/dev/null | head -1 || echo "Unknown")
        echo "✅ Foundry: $FORGE_VERSION"
    else
        echo "❌ Foundry: Not installed"
    fi
    
    # Check cast
    if command -v cast >/dev/null 2>&1; then
        CAST_VERSION=$(cast --version 2>/dev/null | head -1 || echo "Unknown")
        echo "✅ Cast: $CAST_VERSION"
    else
        echo "❌ Cast: Not installed"
    fi
    
    # Check bc
    if command -v bc >/dev/null 2>&1; then
        echo "✅ bc: Installed"
    else
        echo "❌ bc: Not installed"
    fi
    
    # Check jq
    if command -v jq >/dev/null 2>&1; then
        JQ_VERSION=$(jq --version 2>/dev/null || echo "Unknown")
        echo "✅ jq: $JQ_VERSION"
    else
        echo "⚠️  jq: Not installed (optional)"
    fi
    
    # Check curl
    if command -v curl >/dev/null 2>&1; then
        CURL_VERSION=$(curl --version 2>/dev/null | head -1 || echo "Unknown")
        echo "✅ curl: $CURL_VERSION"
    else
        echo "❌ curl: Not installed"
    fi
    echo ""
}

# Update dependencies
update_dependencies() {
    echo "=== Updating Dependencies ==="
    echo ""
    
    # Update Foundry
    if command -v forge >/dev/null 2>&1; then
        echo "Updating Foundry..."
        foundryup 2>/dev/null || echo "⚠️  foundryup not available"
    fi
    
    # Update system packages
    echo "Updating system packages..."
    sudo apt update && sudo apt upgrade -y 2>/dev/null || echo "⚠️  Requires sudo"
    echo ""
}

# Security audit
audit_dependencies() {
    echo "=== Dependency Security Audit ==="
    echo ""
    echo "1. ✅ Check for known vulnerabilities"
    echo "2. ✅ Review dependency versions"
    echo "3. ✅ Pin dependency versions for stability"
    echo "4. ✅ Regular security audits"
    echo ""
    echo "Recommendations:"
    echo "- Pin Foundry version in foundry.toml"
    echo "- Regular security updates"
    echo "- Monitor for security advisories"
    echo ""
}

case "$ACTION" in
    check) check_dependencies ;;
    update) update_dependencies ;;
    audit) audit_dependencies ;;
    *)
        echo "Usage: $0 [check|update|audit]"
        exit 1
        ;;
esac

