const path = require('path');
require('dotenv').config({ path: path.resolve(__dirname, '../../.env') });
const db = require('../db');

async function updateLessonContent(taskId, title, content) {
    try {
        await db.query('UPDATE lesson_content SET content = ? WHERE task_id = ?', [content, taskId]);
        console.log(`✅ Updated: [${taskId}] ${title}`);
    } catch (error) {
        console.error(`❌ Error updating [${taskId}] ${title}:`, error.message);
    }
}

const lessons = [
    // --- MODULE 4: EMAIL SECURITY ---
    {
        id: 364,
        title: "Analyzing Email Headers",
        content: `# 📧 Analyzing Email Headers

Headers reveal the true journey of an email.

## 📝 The Raw Log (RFC 5322)

\`\`\`text
Return-Path: <hacker@evil.com>
Received: from mail.evil.com (mail.evil.com. [185.10.10.10])
        by mx.google.com with ESMTPS id ...
        for <ceo@company.com>
From: "IT Support" <support@company.com>
Subject: URGENT: Password Expiry
Reply-To: support-team@evil.com
X-Originating-IP: [185.10.10.10]
\`\`\`

## 🕵️‍♂️ Investigation Steps

### Step 1: "From" vs "Return-Path"
* **From**: \`support@company.com\` (This is what the user sees. It is easily spoofed).
* **Return-Path**: \`hacker@evil.com\` (This is where bounce errors go. Often reveals the true sender).

### Step 2: "Reply-To"
* **Value**: \`support-team@evil.com\`.
* **Trap**: If the user clicks "Reply", it won't go to IT Support. It will go to the hacker.

### Step 3: X-Originating-IP
* **IP**: \`185.10.10.10\`.
* **GeoLocation**: Check this IP. If IT Support is in New York, why is the email coming from Russia?
`
    },
    {
        id: 365,
        title: "SPF, DKIM, DMARC",
        content: `# 🛡️ SPF, DKIM, DMARC

The three musketeers of email authentication.

## 📝 The Raw Log (Authentication-Results)

\`\`\`text
Authentication-Results: mx.google.com;
       spf=fail (google.com: domain of hacker@evil.com does not designate 185.10.10.10 as permitted sender) smtp.mailfrom=hacker@evil.com;
       dkim=neutral (no signature);
       dmarc=fail (p=REJECT sp=REJECT dis=REJECT) header.from=company.com
\`\`\`

## 🕵️‍♂️ Investigation Steps

### Step 1: SPF (Sender Policy Framework)
* **Status**: \`fail\`.
* **Meaning**: The IP address sending the email is NOT on the approved list for the domain.

### Step 2: DKIM (DomainKeys Identified Mail)
* **Status**: \`neutral (no signature)\`.
* **Meaning**: The email was not legally signed by the server. It could have been modified in transit.

### Step 3: DMARC (Domain-based Message Authentication)
* **Status**: \`fail\`.
* **Policy (p)**: \`REJECT\`.
* **Result**: The receiving server (Google) obeyed the policy and blocked the email. The user never saw it.
`
    },
    {
        id: 366,
        title: "Malicious Attachment Analysis",
        content: `# 📎 Malicious Attachment Analysis

## 📝 The Evidence
* **Filename**: \`Invoice_2024.doc\`
* **Type**: OLE Composite Document
* **Hash**: \`e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855\`

## 📝 The Raw Log (Macro Code)

\`\`\`vba
Sub AutoOpen()
    Dim str As String
    str = "pow" & "ers" & "hell.exe -nop -c IEX..."
    Shell str, vbHide
End Sub
\`\`\`

## 🕵️‍♂️ Investigation Steps

### Step 1: AutoOpen
* **Function**: \`AutoOpen()\`.
* **Behavior**: This code runs **automatically** the moment the victim enables editing.

### Step 2: String Concatenation
* **Code**: \`"pow" & "ers" & "hell.exe"\`.
* **Reason**: Obfusation. The attacker chops up the word "powershell" to bypass simple antivirus signatures.

### Step 3: Execution
* \`Shell str, vbHide\`: Runs the command hidden. The user sees a blank Word doc while their PC is being encrypted.
`
    },
    {
        id: 367,
        title: "Phishing vs Spear Phishing",
        content: `# 🎣 Phishing Types

## 📝 The Scenario
**Email 1**: "Dear Customer, your Netflix is expired. Click here."
**Email 2**: "Hi Bob, I enjoyed our meeting about Project X in London. Please review the attached contract."

## 🕵️‍♂️ Investigation Steps

### Analysis of Email 1 (Bulk Phishing)
* **Greeting**: Generic ("Dear Customer").
* **Urgency**: High ("Expired").
* **Targeting**: None. Sent to millions.

### Analysis of Email 2 (Spear Phishing)
* **Greeting**: Personalized ("Hi Bob").
* **Context**: specific ("Project X", "London").
* **Source**: The attacker likely researched Bob on LinkedIn.
* **Danger**: Extremely high. Users trust context.

### 🛡️ Defense
For Spear Phishing, you rely on **User Awareness Training**. Technology often misses the context, but a human might spot that "Project X" was cancelled last week.
`
    },
    {
        id: 368,
        title: "URL Analysis",
        content: `# 🔗 URL Analysis

## 📝 The Raw Link
\`http://www.paypal.com.secure-login-updates.xyz/login.php\`

## 🕵️‍♂️ Investigation Steps

### Step 1: The Root Domain
* **Reading**: Read from Right to Left.
* **TLD**: \`.xyz\` (Cheap, often malicious).
* **Domain**: \`secure-login-updates.xyz\`.
* **Subdomains**: \`www.paypal.com\`.

### Step 2: Homoglyphs
* Look closely at: \`p\u0430ypal.com\`.
* The 'a' might be a Cyrillic character (IDN Homograph Attack). Use a "Punycode Converter" to check.
* Real: \`paypal.com\`.
* Fake: \`xn--pypal-4ve.com\`.

### Step 3: Sandboxing
* Paste the URL into **UrlScan.io**.
* Look at the screenshot. Does it look like the real PayPal login page?
* If yes, it is a credential harvester.
`
    },

    // --- MODULE 5: VULNERABILITY MANAGEMENT ---
    {
        id: 369,
        title: "CVSS Scoring System",
        content: `# 💯 CVSS Scoring System

Understanding the Common Vulnerability Scoring System (v3.1).

## 📝 The Raw Vector
\`CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H\`

## 🕵️‍♂️ Investigation Steps

### Step 1: Attack Vector (AV)
* **AV:N (Network)**: The vulnerability can be exploited remotely over the internet. (BAD)
* **AV:P (Physical)**: You need to touch the device (USB). (Less critical).

### Step 2: Complexity & Privileges
* **AC:L (Low Complexity)**: A script kiddie can do it.
* **PR:N (None)**: No login required.
* **UI:N (None)**: No user interaction required.

### Step 3: CIA Impact
* **C:H (Confidentiality High)**: They steal all data.
* **I:H (Integrity High)**: They change all data.
* **A:H (Availability High)**: They delete everything.

### Score
* **9.8 CRITICAL**. Drop everything and patch this.
`
    },
    {
        id: 370,
        title: "Prioritizing Patches",
        content: `# 🏥 Prioritizing Patches

You have 10,000 vulnerabilities. You can patch 50. Which ones?

## 📝 The Scenario
1. **Server A**: Internal Test Server. Vulnerability: Score 10.0 (RCE).
2. **Server B**: External Web Server. Vulnerability: Score 7.5 (SQLi).

## 🕵️‍♂️ Decision Steps

### Step 1: Exposure
* **Server B** is reachable from the internet. Attackers are scanning it 24/7.
* **Server A** is behind a firewall. Attackers need to be inside first.

### Step 2: Exploitability
* Is there a Metasploit module for the SQLi? Yes.
* Is the RCE theoretical? Yes.

### Step 3: Business Impact
* If Web Server goes down, we lose money.
* If Test Server goes down, devs preserve coffee.

### 🏆 Verdict
**Patch Server B first**. Context matters more than raw score.
`
    },
    {
        id: 371,
        title: "False Positives",
        content: `# 🤥 False Positives

## 📝 The Scan Result
**Vulnerability**: Apache < 2.4.49 Path Traversal.
**Detected Version**: Apache/2.4.46 (Ubuntu).
**Status**: VULNERABLE.

## 🕵️‍♂️ Investigation Steps

### Step 1: Check the Distribution
* Linux distros (Ubuntu/RedHat) do "Backporting". They take security fixes from new versions and apply them to old versions to maintain stability.

### Step 2: Check the Changelog
* Run: \`apt-get changelog apache2 | grep CVE-2021-41773\`.
* Output: \`Fixed CVE-2021-41773 in 2.4.46-1ubuntu1.2\`.

### Step 3: Verdict
* It looks like 2.4.46, but it HAS the patch.
* **Mark as False Positive**.
`
    },
    {
        id: 372,
        title: "Authenticated vs Unauthenticated Scanning",
        content: `# 🔐 Scan Types

## 📝 The Comparison

### Unauthenticated Scan
* **Perspective**: External Attacker.
* **Method**: Port scanning, banner grabbing (\`Server: Apache/2.4\`), checking default pages.
* **Pros**: Fast, realistic external view.
* **Cons**: Misses everything inside (e.g., outdated Chrome browser installed on the OS).

### Authenticated Scan
* **Perspective**: Insider / Compromised Host.
* **Method**: Scanner logs in with credentials (SSH/SMB) and runs commands (\`rpm -qa\`, \`reg query\`).
* **Pros**: 100% accurate inventory. Finds missing patches in Adobe Reader, Java, etc.
* **Cons**: Needs credentials (risk).
`
    },
    {
        id: 373,
        title: "Remediation Reports",
        content: `# 📋 Remediation Reports

Developers hate 500-page PDF reports.

## 📝 Bad Report
"Here is a list of 5,000 IPs with vulnerabilities. Fix them."

## 📝 Good Report (Actionable)
**Vulnerability**: Log4Shell (CVE-2021-44228).
**Impact**: Remote Code Execution (Critical).
**Affected Assets**: 12 Public Facing Servers (List attached).
**Fix**:
1. Upgrade \`log4j\` to version 2.17.1.
2. OR: Set environment variable \`LOG4J_FORMAT_MSG_NO_LOOKUPS=true\`.
**Deadline**: 24 Hours.
**Verification**: We will re-scan on Friday at 5 PM.
`
    }
];

// Execute Updates
(async () => {
    console.log('🚀 Updating Module 4 & 5 with Raw Logs...');
    for (const lesson of lessons) {
        await updateLessonContent(lesson.id, lesson.title, lesson.content);
    }
    console.log('✨ Module 4 & 5 Update Complete.');
    process.exit(0);
})();
