const db = require('../db');

const overview = {
    id: 42,
    title: 'Container Security',
    description: 'Secure Docker, Kubernetes, and container orchestration environments.',
    learning_path_id: 4
};

const tasks = [
    { id: 421, title: 'Container Security Fundamentals' },
    { id: 422, title: 'Docker Security Hardening' },
    { id: 423, title: 'Kubernetes Security' },
    { id: 424, title: 'Container Image Security' },
    { id: 425, title: 'Runtime Protection' },
    { id: 426, title: 'Final Quiz' }
];

const lessons = {
    421: {
        content: `# Container Security Fundamentals

Containers are not VMs. Security is different.

## Container vs VM Isolation
*   **VM**: Full OS kernel isolation (hardware-level via hypervisor).
*   **Container**: Shared kernel, namespace isolation (process-level).

**Implication**: Container escape = Host compromise.

## Attack Surface
*   **Host Kernel**: Shared by all containers.
*   **Container Runtime**: Docker daemon, containerd.
*   **Orchestrator**: Kubernetes API server.
*   **Images**: Supply chain attacks.
*   **Network**: Container-to-container, egress.

## Shared Responsibility
| Layer | Responsibility |
|-------|----------------|
| Cloud Infrastructure | Cloud Provider |
| Kubernetes Control Plane | Managed (EKS/GKE) or You |
| Worker Nodes | You |
| Container Images | You |
| Application Code | You |

## Key Standards
*   **CIS Docker Benchmark**: Hardening guide.
*   **CIS Kubernetes Benchmark**: K8s security controls.
*   **NIST 800-190**: Container Security Guide.`,
        questions: [
            ['How does container isolation differ from VMs?', 'Containers share the host kernel; VMs have full kernel isolation', 'Kernel', ['No difference', 'Containers share the host kernel; VMs have full kernel isolation', 'VMs are less secure', 'Containers are slower']],
            ['What is the risk of container escape?', 'Attacker gains access to the host and other containers', 'Host', ['Nothing', 'Attacker gains access to the host and other containers', 'Container restarts', 'Performance drop']],
            ['What standard provides Kubernetes hardening guidance?', 'CIS Kubernetes Benchmark', 'CIS', ['ISO 27001', 'CIS Kubernetes Benchmark', 'PCI DSS', 'HIPAA']]
        ]
    },
    422: {
        content: `# Docker Security Hardening

Secure the Docker daemon and containers.

## Docker Daemon Hardening
*   **No root**: Run containers as non-root user.
*   **Read-only filesystem**: \`--read-only\` flag.
*   **No privileged mode**: Never use \`--privileged\` unless absolutely necessary.
*   **Drop capabilities**: Remove unnecessary Linux capabilities.
*   **Limit resources**: CPU/memory limits prevent DoS.

## Dockerfile Best Practices
\`\`\`dockerfile
# Use minimal base image
FROM alpine:3.18

# Don't run as root
RUN adduser -D appuser
USER appuser

# Copy only what's needed
COPY --chown=appuser:appuser app /app

# No secrets in image
# Use secrets mounting at runtime
\`\`\`

## Security Options
\`\`\`bash
docker run \\
  --read-only \\
  --cap-drop=ALL \\
  --cap-add=NET_BIND_SERVICE \\
  --security-opt=no-new-privileges \\
  --user 1000:1000 \\
  myapp:latest
\`\`\`

## Audit Docker
*   Use Docker Bench Security: \`docker-bench-security\`.
*   Scans against CIS Benchmark.`,
        questions: [
            ['Why avoid --privileged flag?', 'It gives the container full host capabilities', 'Root', ['It is slow', 'It gives the container full host capabilities', 'It uses more memory', 'No reason']],
            ['What does --cap-drop=ALL do?', 'Removes all Linux capabilities from the container', 'Least privilege', ['Adds capabilities', 'Removes all Linux capabilities from the container', 'Drops the container', 'Deletes files']],
            ['Which tool audits Docker against CIS Benchmark?', 'Docker Bench Security', 'Audit', ['Nmap', 'Docker Bench Security', 'Wireshark', 'Burp Suite']]
        ]
    },
    423: {
        content: `# Kubernetes Security

Secure the orchestration layer.

## Control Plane Security
*   **API Server**: Enable RBAC, use TLS, audit logging.
*   **etcd**: Encrypt at rest, restrict access.
*   **Kubelet**: Disable anonymous auth, use TLS.

## RBAC (Role-Based Access Control)
\`\`\`yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  namespace: production
  name: pod-reader
rules:
- apiGroups: [""]
  resources: ["pods"]
  verbs: ["get", "list"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: read-pods
  namespace: production
subjects:
- kind: User
  name: alice
roleRef:
  kind: Role
  name: pod-reader
\`\`\`

## Pod Security
*   **Pod Security Standards**: Privileged, Baseline, Restricted.
*   **Security Context**:
\`\`\`yaml
securityContext:
  runAsNonRoot: true
  readOnlyRootFilesystem: true
  allowPrivilegeEscalation: false
\`\`\`

## Network Policies
*   Default: All pods can talk to all pods.
*   Use NetworkPolicy to restrict traffic.`,
        questions: [
            ['What does RBAC control in Kubernetes?', 'Who can do what to which resources', 'Access', ['Network traffic', 'Who can do what to which resources', 'Storage', 'Logging']],
            ['What is the most restrictive Pod Security Standard?', 'Restricted', 'Strict', ['Privileged', 'Baseline', 'Restricted', 'None']],
            ['Why use NetworkPolicy?', 'Restrict pod-to-pod communication', 'Segmentation', ['Faster network', 'Restrict pod-to-pod communication', 'More pods', 'Easier config']]
        ]
    },
    424: {
        content: `# Container Image Security

The supply chain is a major attack vector.

## Image Scanning
*   Scan for known vulnerabilities (CVEs).
*   Tools: **Trivy**, **Grype**, **Clair**, **Snyk**.

## Trivy Example
\`\`\`bash
trivy image nginx:latest
# Output: CVEs found with severity ratings
\`\`\`

## Image Provenance
*   **Sign images**: Docker Content Trust, Sigstore/Cosign.
*   **Verify in CI/CD**: Reject unsigned images.
*   **Admission Controllers**: Kubernetes can enforce signed images.

## Base Image Selection
| Choice | Security |
|--------|----------|
| Alpine | Minimal, fewer CVEs |
| Distroless | No shell, minimal attack surface |
| Full OS (Ubuntu) | More CVEs, easier to debug |

## CI/CD Pipeline Security
\`\`\`
Build → Scan → Sign → Push → Admission Control → Deploy
         ↓
    Fail if Critical CVE
\`\`\`

## Registry Security
*   Private registry with access control.
*   Scan on push.
*   Delete unused/old images.`,
        questions: [
            ['Which tool scans container images for CVEs?', 'Trivy', 'Scanner', ['Nmap', 'Trivy', 'Wireshark', 'Metasploit']],
            ['What is Distroless?', 'Container images with no shell or package manager', 'Minimal', ['A Linux distro', 'Container images with no shell or package manager', 'A Docker command', 'A network tool']],
            ['Why sign container images?', 'Verify provenance and prevent tampering', 'Trust', ['Faster pulls', 'Verify provenance and prevent tampering', 'Smaller size', 'No reason']]
        ]
    },
    425: {
        content: `# Runtime Protection

Detect and prevent attacks at runtime.

## Runtime Threats
*   Container escape.
*   Cryptomining.
*   Reverse shells.
*   Data exfiltration.
*   Malicious process execution.

## Runtime Security Tools
| Tool | Capability |
|------|------------|
| **Falco** | Open-source runtime security (syscall monitoring) |
| **Sysdig Secure** | Commercial, extends Falco |
| **Aqua** | Full lifecycle container security |
| **Prisma Cloud** | Palo Alto's CNAPP |

## Falco Example Rule
\`\`\`yaml
- rule: Terminal shell in container
  desc: Detect shell in container
  condition: >
    spawned_process and container and
    proc.name in (bash, sh, zsh)
  output: "Shell spawned in container (user=%user.name container=%container.name)"
  priority: WARNING
\`\`\`

## Behavioral Baselines
*   Learn what normal looks like for each container.
*   Alert on deviation (new process, new network connection).

## Response Actions
*   Kill container.
*   Pause for investigation.
*   Alert and log for review.`,
        questions: [
            ['What does Falco monitor?', 'System calls (syscalls) at runtime', 'Syscall', ['Network only', 'System calls (syscalls) at runtime', 'Files only', 'Nothing']],
            ['What is a behavioral baseline?', 'Profile of normal container behavior to detect anomalies', 'Normal', ['A security tool', 'Profile of normal container behavior to detect anomalies', 'A network policy', 'A log file']],
            ['What action can runtime security take on a threat?', 'Kill, pause, or alert on the container', 'Response', ['Nothing', 'Kill, pause, or alert on the container', 'Only log', 'Restart host']]
        ]
    },
    426: {
        content: `# Final Quiz

Test your Container Security knowledge.`,
        questions: [
            ['Containers share what with the host?', 'The kernel', 'Shared', ['Nothing', 'The kernel', 'The filesystem only', 'Memory only']],
            ['What does --cap-drop=ALL do?', 'Removes all Linux capabilities', 'Restrict', ['Adds capabilities', 'Removes all Linux capabilities', 'Drops container', 'Nothing']],
            ['Which tool scans images for CVEs?', 'Trivy', 'Scanner', ['Nmap', 'Trivy', 'Docker', 'Kubernetes']],
            ['What does RBAC control?', 'Who can access which resources', 'Access', ['Network', 'Who can access which resources', 'Storage', 'CPU']],
            ['What does Falco monitor?', 'System calls at runtime', 'Runtime', ['Images', 'System calls at runtime', 'Network only', 'Logs']],
            ['Why use minimal base images?', 'Fewer vulnerabilities, smaller attack surface', 'Less CVEs', ['Faster', 'Fewer vulnerabilities, smaller attack surface', 'Prettier', 'Cheaper']]
        ]
    }
};

async function createModule() {
    try {
        console.log('🚀 Creating Module 42: Container Security...\n');
        await db.query(`INSERT INTO modules (id, title, description, display_order, learning_path_id) VALUES (?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE title = VALUES(title), description = VALUES(description)`, 
            [overview.id, overview.title, overview.description, overview.id, overview.learning_path_id]);
        for (const t of tasks) {
            await db.query(`INSERT INTO tasks (id, module_id, title, is_active, display_order) VALUES (?, ?, ?, 1, ?) ON DUPLICATE KEY UPDATE title = VALUES(title), module_id = VALUES(module_id), is_active=1`,
                [t.id, overview.id, t.title, t.id]);
        }
        for (const [idStr, lesson] of Object.entries(lessons)) {
            const taskId = parseInt(idStr);
            await db.query('DELETE FROM lesson_content WHERE task_id = ?', [taskId]);
            await db.query('DELETE FROM lesson_questions WHERE task_id = ?', [taskId]);
            await db.query('INSERT INTO lesson_content (task_id, content, content_type, reading_time_minutes) VALUES (?, ?, ?, ?)',
                [taskId, lesson.content, 'markdown', 20]);
            for (let j = 0; j < lesson.questions.length; j++) {
                const q = lesson.questions[j];
                await db.query('INSERT INTO lesson_questions (task_id, question_text, correct_answer, question_order, hint, options, case_sensitive) VALUES (?, ?, ?, ?, ?, ?, ?)',
                    [taskId, q[0], q[1], j + 1, q[2], JSON.stringify(q[3]), 0]);
            }
        }
        console.log(`✅ Module 42 Created!\n`);
        process.exit(0);
    } catch (error) {
        console.error('Error:', error);
        process.exit(1);
    }
}
createModule();
