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 = [
    {
        id: 359,
        title: "Writing SPL (Search Processing Language)",
        content: `# 🔎 Writing SPL

Search Processing Language (SPL) is the standard for querying big data in Splunk.

## 📝 The Scenario
Your boss says "Find all failed logins from China in the last 24 hours."

## 📝 The Raw Query (SPL)

\`\`\`splunk
index=main sourcetype=wineventlog:security EventCode=4625 
| iplocation SourceNetworkAddress 
| search Country="China"
| stats count by SourceNetworkAddress, User
| sort - count
\`\`\`

## 🕵️‍♂️ Investigation Steps

### Step 1: Filter Phase
* \`index=main\`: Search only the main storage.
* \`EventCode=4625\`: Windows Failed Identity.

### Step 2: Enrichment
* \`iplocation\`: Splunk automatically adds \`Country\`, \`City\`, \`Lat\`, \`Lon\` based on the IP address.

### Step 3: Aggregation
* \`stats count by...\`: Instead of showing 10,000 individual log lines, show me a table.
* **Row 1**: IP \`1.2.3.4\`, User \`Admin\`, Count \`500\`.
* **Conclusion**: We are under a brute force attack.
`
    },
    {
        id: 360,
        title: "Correlating Events",
        content: `# 🔗 Correlating Events

A single log is a dot. Correlation connects the dots to make a picture.

## 📝 The Raw Logs (Sequence)

\`\`\`text
[09:00:01] Failed Login (User: Bob, IP: 10.0.0.50)
[09:00:02] Failed Login (User: Bob, IP: 10.0.0.50)
[09:00:03] Failed Login (User: Bob, IP: 10.0.0.50)
... (50 more times)
[09:01:00] Successful Login (User: Bob, IP: 10.0.0.50)
[09:01:05] User Created (User: Admin2, By: Bob)
\`\`\`

## 🕵️‍♂️ Investigation Steps

### Step 1: Brute Force
* The first block is a classic brute force attack.

### Step 2: The Breakthrough
* \`[09:01:00]\`: The attack succeeded. They guessed the password.

### Step 3: Persistence
* \`[09:01:05]\`: The very first thing the attacker did was create a BACKDOOR user (\`Admin2\`).
* **Why**: Even if Bob changes his password, the attacker can still login as Admin2.

### Step 4: The Correlation Rule
* \`Trigger Alert IF (Failed_Login > 10 in 5 mins) FOLLOWED BY (Successful_Login)\`.
`
    },
    {
        id: 361,
        title: "Windows Event Codes",
        content: `# 🆔 Windows Event Codes

You must memorize these.

## 📝 The Cheat Sheet

| ID | Name | Significance |
| :--- | :--- | :--- |
| **4624** | Logon Successful | Who got in? Type 2 (Interactive), Type 3 (Network), Type 10 (RDP). |
| **4625** | Logon Failed | Brute force detection. Check "Sub Status" for reason (bad password vs locked out). |
| **4720** | User Created | Persistence. Did HR authorize a new employee today? |
| **4672** | Special Privileges | Admin logon. "SeDebugPrivilege" usage. |
| **1102** | Log Cleared | **RED FLAG**. Only hackers and bad admins clear logs. |

## 📝 The Raw Log (Event 1102)

\`\`\`xml
<EventID>1102</EventID>
<Data Name='UserData'>The audit log was cleared.</Data>
<Data Name='SubjectUserName'>Administrator</Data>
\`\`\`

## 🕵️‍♂️ Investigation Steps
1. **Immediate Escalation**.
2. Isolate the host.
3. Assume extensive compromise.
`
    },
    {
        id: 362,
        title: "Linux Syslog Analysis",
        content: `# 🐧 Linux Syslog Analysis

Linux logs are text-based and usually found in \`/var/log\`.

## 📝 The Raw Log (Sudo Abuse)

\`\`\`text
Mar 15 14:22:01 ubuntu-server sudo:   asmith : TTY=pts/0 ; PWD=/home/asmith ; USER=root ; COMMAND=/bin/bash
\`\`\`

## 🕵️‍♂️ Investigation Steps

### Step 1: The Command
* \`COMMAND=/bin/bash\`.
* **Translation**: The user \`asmith\` used \`sudo\` (SuperUser Do) to become root (Administrator).
* **Impact**: They spawned a generic shell. They can now delete any file, install any software, or wipe the server.

### Step 2: Context
* Is \`asmith\` a SysAdmin?
* If this is a Web Developer, why do they need root shell access?
* If they need to restart a service, they should run \`sudo systemctl restart nginx\`, NOT \`sudo bash\`.
`
    },
    {
        id: 363,
        title: "Baseline vs Anomaly",
        content: `# 📊 Baseline vs Anomaly

You cannot find "Evil" if you don't know "Normal".

## 📝 The Anomaly Log (UEBA)

\`\`\`json
{
  "alert": "Impossible Travel",
  "user": "jsmith",
  "login_1": { "time": "10:00:00Z", "location": "New York, USA" },
  "login_2": { "time": "11:00:00Z", "location": "London, UK" }
}
\`\`\`

## 🕵️‍♂️ Investigation Steps

### Step 1: Physics Check
* **Distance**: NY to London is ~3,500 miles.
* **Time**: 1 Hour.
* **Speed Required**: 3,500 MPH.
* **Conclusion**: Unless Jsmith is Superman, this is physically impossible.

### Step 2: VPN Check
* Is the user on a corporate VPN that tunnels traffic?
* If Login 1 was Home and Login 2 was Corporate VPN (which exits in London), this might be a false positive.

### Step 3: Concurrent Sessions
* If both sessions are active at the same time, the credentials have been shared or stolen.
`
    }
];

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