#!/bin/bash
# Module 7: Networks

cat << 'EOF'
---

## 7️⃣ NETWORKS

### Docker Networks Overview

EOF

NETWORK_COUNT=$(docker network ls | grep -v NETWORK | wc -l)
echo "**Total Networks:** $NETWORK_COUNT"
echo ""
echo "### Network Details"
echo ""

docker network ls --format '{{.Name}}|{{.Driver}}|{{.Scope}}' | grep -v 'NETWORK' | while IFS='|' read -r name driver scope; do
    CONTAINERS=$(docker network inspect "$name" -f '{{range .Containers}}{{.Name}}, {{end}}' 2>/dev/null | sed 's/, $//')
    CONTAINER_COUNT=$(echo "$CONTAINERS" | grep -o ',' | wc -l)
    ((CONTAINER_COUNT++))
    
    SUBNET=$(docker network inspect "$name" -f '{{range .IPAM.Config}}{{.Subnet}}{{end}}' 2>/dev/null)
    GATEWAY=$(docker network inspect "$name" -f '{{range .IPAM.Config}}{{.Gateway}}{{end}}' 2>/dev/null)
    
    if [[ -z "$CONTAINERS" ]]; then
        CONTAINERS="(no containers attached)"
        CONTAINER_COUNT=0
    fi
    
    cat << NETINFO

#### 🌐 **$name**

- **Driver:** $driver
- **Scope:** $scope
- **Subnet:** ${SUBNET:-N/A}
- **Gateway:** ${GATEWAY:-N/A}
- **Connected Containers:** $CONTAINER_COUNT
- **Container List:** $CONTAINERS

NETINFO
done

cat << 'EOF'

### Network Management Commands

```bash
# List all networks
docker network ls

# Inspect network
docker network inspect <network-name>

# Create new network
docker network create --driver bridge my-network

# Connect container to network
docker network connect <network-name> <container-name>

# Disconnect container from network
docker network disconnect <network-name> <container-name>

# Remove unused networks
docker network prune -f
```

### Common Network Issues

#### Container can't reach another container

```bash
# Check if both are on same network
docker network inspect <network-name>

# Check container IP
docker inspect <container-name> | grep IPAddress

# Test connectivity
docker exec <container1> ping <container2>
```

#### DNS resolution not working

```bash
# Check Docker DNS
docker exec <container> cat /etc/resolv.conf

# Test DNS
docker exec <container> nslookup google.com

# Restart Docker daemon if needed
sudo systemctl restart docker
```
EOF
