#!/usr/bin/env bash

# Security Scan Script
# This script runs security scans on containers and smart contracts

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/../lib/init.sh"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"


log_success "Running Security Scans..."

# Container image scanning
log_warn "Scanning container images..."

IMAGES=(
    "hyperledger/besu:23.10.0"
    "blockscout/blockscout:v5.1.5"
    "prom/prometheus:v2.45.0"
    "grafana/grafana:10.1.0"
    "busybox:1.36"
)

# Check if trivy is available
if command -v trivy &> /dev/null; then
    log_success "✓ Trivy is available"
    
    for image in "${IMAGES[@]}"; do
        log_warn "Scanning $image..."
        if trivy image --severity HIGH,CRITICAL "$image" 2>&1 | tee /tmp/trivy-scan-$(echo $image | tr '/:' '-').log; then
            log_success "✓ Scan completed for $image"
        else
            log_warn "⚠ Scan completed with issues for $image (check logs)"
        fi
    done
else
    log_warn "⚠ Trivy not available. Install it for container scanning:"
    echo "  https://aquasecurity.github.io/trivy/latest/getting-started/installation/"
fi

# Smart contract security scanning
log_warn "Scanning smart contracts..."

# Check if slither is available
if command -v slither &> /dev/null; then
    log_success "✓ Slither is available"
    
    CONTRACTS=(
        "contracts/oracle/Aggregator.sol"
        "contracts/oracle/Proxy.sol"
        "contracts/tokens/WETH.sol"
        "contracts/utils/Multicall.sol"
        "contracts/utils/CREATE2Factory.sol"
    )
    
    for contract in "${CONTRACTS[@]}"; do
        if [ -f "$PROJECT_ROOT/$contract" ]; then
            log_warn "Scanning $contract..."
            if slither "$PROJECT_ROOT/$contract" 2>&1 | tee /tmp/slither-scan-$(basename $contract .sol).log; then
                log_success "✓ Scan completed for $contract"
            else
                log_warn "⚠ Scan completed with issues for $contract (check logs)"
            fi
        fi
    done
else
    log_warn "⚠ Slither not available. Install it for smart contract scanning:"
    echo "  pip install slither-analyzer"
fi

# Foundry security tests
log_warn "Running Foundry security tests..."

if command -v forge &> /dev/null; then
    log_success "✓ Foundry is available"
    
    cd "$PROJECT_ROOT"
    
    # Run tests
    if forge test --gas-report 2>&1 | tee /tmp/foundry-tests.log; then
        log_success "✓ Foundry tests passed"
    else
        log_warn "⚠ Some Foundry tests failed (check logs)"
    fi
    
    # Run fuzz tests
    if forge test --fuzz-runs 1000 2>&1 | tee /tmp/foundry-fuzz.log; then
        log_success "✓ Foundry fuzz tests passed"
    else
        log_warn "⚠ Some Foundry fuzz tests failed (check logs)"
    fi
else
    log_warn "⚠ Foundry not available. Install it for testing:"
    echo "  https://book.getfoundry.sh/getting-started/installation"
fi

# Dependency scanning
log_warn "Scanning dependencies..."

# Python dependencies
if [ -f "$PROJECT_ROOT/services/oracle-publisher/requirements.txt" ]; then
    log_warn "Scanning Python dependencies..."
    if command -v safety &> /dev/null; then
        if safety check --file "$PROJECT_ROOT/services/oracle-publisher/requirements.txt" 2>&1 | tee /tmp/safety-scan.log; then
            log_success "✓ Python dependencies scan completed"
        else
            log_warn "⚠ Python dependencies scan found issues (check logs)"
        fi
    else
        log_warn "⚠ Safety not available. Install it for Python dependency scanning:"
        echo "  pip install safety"
    fi
fi

# Node.js dependencies (SDK)
if [ -f "$PROJECT_ROOT/sdk/package.json" ]; then
    log_warn "Scanning Node.js dependencies..."
    if command -v npm &> /dev/null; then
        cd "$PROJECT_ROOT/sdk"
        if npm audit --audit-level=moderate 2>&1 | tee /tmp/npm-audit.log; then
            log_success "✓ Node.js dependencies scan completed"
        else
            log_warn "⚠ Node.js dependencies scan found issues (check logs)"
        fi
    else
        log_warn "⚠ npm not available"
    fi
fi

# Terraform security scanning
log_warn "Scanning Terraform configuration..."

if command -v checkov &> /dev/null; then
    log_success "✓ Checkov is available"
    
    if checkov -d "$PROJECT_ROOT/terraform" --framework terraform 2>&1 | tee /tmp/checkov-scan.log; then
        log_success "✓ Terraform security scan completed"
    else
        log_warn "⚠ Terraform security scan found issues (check logs)"
    fi
else
    log_warn "⚠ Checkov not available. Install it for Terraform scanning:"
    echo "  pip install checkov"
fi

# Kubernetes manifest scanning
log_warn "Scanning Kubernetes manifests..."

if command -v kube-score &> /dev/null; then
    log_success "✓ kube-score is available"
    
    if kube-score score "$PROJECT_ROOT/k8s" -o human 2>&1 | tee /tmp/kube-score-scan.log; then
        log_success "✓ Kubernetes manifest scan completed"
    else
        log_warn "⚠ Kubernetes manifest scan found issues (check logs)"
    fi
else
    log_warn "⚠ kube-score not available. Install it for Kubernetes scanning:"
    echo "  https://github.com/zegl/kube-score#installation"
fi

log_success "Security scanning completed"
log_warn "Scan results are saved in /tmp/*.log"

