#!/bin/bash

# Malware Website Crawler - AWS Cost Monitoring Script
# This script helps monitor AWS costs and identify expensive resources

set -e

echo "💰 AWS Cost Monitoring for Malware Website Crawler"
echo "================================================="
echo ""

# Function to get current month costs
get_current_month_costs() {
    echo "📊 Current Month Costs:"
    echo "======================"
    
    # Get current month start date
    MONTH_START=$(date -d "$(date +%Y-%m-01)" +%Y-%m-%d)
    TODAY=$(date +%Y-%m-%d)
    
    echo "Period: $MONTH_START to $TODAY"
    echo ""
    
    # Get cost by service
    echo "💵 Cost by Service:"
    aws ce get-cost-and-usage \
        --time-period Start=$MONTH_START,End=$TODAY \
        --granularity MONTHLY \
        --metrics BlendedCost \
        --group-by Type=DIMENSION,Key=SERVICE \
        --query 'ResultsByTime[0].Groups[*].[Keys[0],Metrics.BlendedCost.Amount]' \
        --output table 2>/dev/null || echo "   Cost Explorer not available or no permissions"
    
    echo ""
}

# Function to get resource counts
get_resource_counts() {
    echo "📈 Resource Counts:"
    echo "=================="
    
    # ECS Resources
    ECS_CLUSTERS=$(aws ecs list-clusters --query "clusterArns[?contains(@, 'malware-crawler')]" --output text | wc -w)
    ECS_SERVICES=$(aws ecs list-services --cluster malware-crawler-cluster --query "serviceArns" --output text 2>/dev/null | wc -w || echo "0")
    ECS_TASKS=$(aws ecs list-tasks --cluster malware-crawler-cluster --query "taskArns" --output text 2>/dev/null | wc -w || echo "0")
    
    echo "🐳 ECS Resources:"
    echo "   Clusters: $ECS_CLUSTERS"
    echo "   Services: $ECS_SERVICES"
    echo "   Running Tasks: $ECS_TASKS"
    echo ""
    
    # RDS Resources
    RDS_INSTANCES=$(aws rds describe-db-instances --query "DBInstances[?contains(DBInstanceIdentifier, 'malware-crawler')]" --output text | wc -l)
    echo "🗄️  RDS Resources:"
    echo "   Instances: $RDS_INSTANCES"
    echo ""
    
    # ElastiCache Resources
    REDIS_GROUPS=$(aws elasticache describe-replication-groups --query "ReplicationGroups[?contains(ReplicationGroupId, 'malware-crawler')]" --output text | wc -l)
    echo "🔴 ElastiCache Resources:"
    echo "   Redis Groups: $REDIS_GROUPS"
    echo ""
    
    # S3 Resources
    S3_BUCKETS=$(aws s3api list-buckets --query "Buckets[?contains(Name, 'malware-crawler')]" --output text | wc -l)
    echo "💾 S3 Resources:"
    echo "   Buckets: $S3_BUCKETS"
    echo ""
    
    # Load Balancer Resources
    ALBS=$(aws elbv2 describe-load-balancers --query "LoadBalancers[?contains(LoadBalancerName, 'malware-crawler')]" --output text | wc -l)
    echo "⚖️  Load Balancer Resources:"
    echo "   ALBs: $ALBS"
    echo ""
}

# Function to get estimated daily costs
get_estimated_daily_costs() {
    echo "📅 Estimated Daily Costs:"
    echo "========================"
    
    # ECS Fargate (0.5 vCPU, 1GB RAM)
    ECS_DAILY_COST=$(echo "scale=2; (0.04096 * 24) + (0.004096 * 24)" | bc 2>/dev/null || echo "~$1.08")
    echo "🐳 ECS Fargate (1 task): \$$ECS_DAILY_COST/day"
    
    # RDS (db.t3.micro)
    RDS_DAILY_COST=$(echo "scale=2; 0.017 * 24" | bc 2>/dev/null || echo "~$0.41")
    echo "🗄️  RDS PostgreSQL: \$$RDS_DAILY_COST/day"
    
    # ElastiCache (cache.t3.micro)
    REDIS_DAILY_COST=$(echo "scale=2; 0.017 * 24" | bc 2>/dev/null || echo "~$0.41")
    echo "🔴 ElastiCache Redis: \$$REDIS_DAILY_COST/day"
    
    # Application Load Balancer
    ALB_DAILY_COST=$(echo "scale=2; 0.0225 * 24" | bc 2>/dev/null || echo "~$0.54")
    echo "⚖️  Application Load Balancer: \$$ALB_DAILY_COST/day"
    
    # NAT Gateway (2x)
    NAT_DAILY_COST=$(echo "scale=2; 0.045 * 24 * 2" | bc 2>/dev/null || echo "~$2.16")
    echo "🌐 NAT Gateways (2x): \$$NAT_DAILY_COST/day"
    
    # S3 Storage (estimated)
    S3_DAILY_COST="~$0.01"
    echo "💾 S3 Storage (10GB): \$$S3_DAILY_COST/day"
    
    # Data Transfer (estimated)
    TRANSFER_DAILY_COST="~$0.30"
    echo "📡 Data Transfer: \$$TRANSFER_DAILY_COST/day"
    
    echo ""
    TOTAL_DAILY=$(echo "scale=2; 1.08 + 0.41 + 0.41 + 0.54 + 2.16 + 0.01 + 0.30" | bc 2>/dev/null || echo "~$4.91")
    echo "💰 Total Estimated Daily Cost: \$$TOTAL_DAILY"
    echo "💰 Total Estimated Monthly Cost: \$$(echo "scale=2; $TOTAL_DAILY * 30" | bc 2>/dev/null || echo "~$147.30")"
    echo ""
}

# Function to check for expensive resources
check_expensive_resources() {
    echo "⚠️  Expensive Resource Check:"
    echo "============================"
    
    # Check for large ECS tasks
    LARGE_TASKS=$(aws ecs list-task-definitions --family-prefix malware-crawler --query "taskDefinitionArns" --output text 2>/dev/null | wc -w || echo "0")
    if [ "$LARGE_TASKS" -gt 0 ]; then
        echo "🔍 Found $LARGE_TASKS ECS task definitions"
        echo "   Check if any use large instance types (t3.large, etc.)"
    fi
    
    # Check for large RDS instances
    LARGE_RDS=$(aws rds describe-db-instances --query "DBInstances[?contains(DBInstanceIdentifier, 'malware-crawler') && DBInstanceClass != 'db.t3.micro']" --output text 2>/dev/null | wc -l || echo "0")
    if [ "$LARGE_RDS" -gt 0 ]; then
        echo "⚠️  Found $LARGE_RDS non-micro RDS instances"
        echo "   Consider downsizing to db.t3.micro for cost savings"
    fi
    
    # Check for large ElastiCache instances
    LARGE_REDIS=$(aws elasticache describe-replication-groups --query "ReplicationGroups[?contains(ReplicationGroupId, 'malware-crawler') && NodeType != 'cache.t3.micro']" --output text 2>/dev/null | wc -l || echo "0")
    if [ "$LARGE_REDIS" -gt 0 ]; then
        echo "⚠️  Found $LARGE_REDIS non-micro ElastiCache instances"
        echo "   Consider downsizing to cache.t3.micro for cost savings"
    fi
    
    # Check for multiple NAT gateways
    NAT_COUNT=$(aws ec2 describe-nat-gateways --query "NatGateways[?State == 'available' && contains(Tags[?Key=='Name'].Value, 'malware-crawler')]" --output text 2>/dev/null | wc -l || echo "0")
    if [ "$NAT_COUNT" -gt 1 ]; then
        echo "⚠️  Found $NAT_COUNT NAT gateways"
        echo "   Consider using single NAT gateway for cost savings"
    fi
    
    echo ""
}

# Function to provide cost optimization recommendations
cost_optimization_tips() {
    echo "💡 Cost Optimization Tips:"
    echo "========================="
    echo ""
    echo "🔧 Immediate Actions:"
    echo "   • Stop ECS services when not in use"
    echo "   • Use Spot Instances for non-critical workloads"
    echo "   • Enable S3 lifecycle policies to delete old files"
    echo "   • Set up CloudWatch billing alerts"
    echo ""
    echo "📊 Resource Optimization:"
    echo "   • Use t3.micro instances for development"
    echo "   • Implement auto-scaling to scale down during low usage"
    echo "   • Use single NAT gateway instead of multiple"
    echo "   • Enable RDS automated backups with shorter retention"
    echo ""
    echo "🕐 Scheduling:"
    echo "   • Schedule ECS services to stop during off-hours"
    echo "   • Use AWS Lambda for batch processing instead of always-on services"
    echo "   • Implement cost-aware scheduling for non-production environments"
    echo ""
}

# Main execution
echo "🔍 Gathering cost information..."
echo ""

get_resource_counts
get_estimated_daily_costs
check_expensive_resources

# Try to get actual costs (requires Cost Explorer permissions)
if aws ce get-cost-and-usage --time-period Start=$(date -d "$(date +%Y-%m-01)" +%Y-%m-%d),End=$(date +%Y-%m-%d) --granularity MONTHLY --metrics BlendedCost --query 'ResultsByTime[0].Total.BlendedCost.Amount' --output text 2>/dev/null | grep -q "0.00"; then
    echo "📊 No costs found or Cost Explorer not available"
else
    get_current_month_costs
fi

cost_optimization_tips

echo "✅ Cost monitoring completed!"
echo ""
echo "💡 To set up billing alerts:"
echo "   aws cloudwatch put-metric-alarm --alarm-name 'High-AWS-Cost' --alarm-description 'Alert when AWS costs exceed threshold' --metric-name EstimatedCharges --namespace AWS/Billing --statistic Maximum --period 86400 --threshold 100 --comparison-operator GreaterThanThreshold"
