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

async function seedModule2Lessons() {
    try {
        console.log('Starting to seed Module 2 (Linux Basics) lessons...\n');

        // Task 6: Navigating the File System
        const task6Content = `# Navigating the Linux File System

Understanding the Linux file system structure and how to navigate it is fundamental to working in cybersecurity. Whether you're analyzing logs, hunting for malware, or investigating incidents, you'll spend significant time navigating directories.

## The Linux Directory Structure

Linux organizes files in a hierarchical tree structure, starting from the root directory (\`/\`).

### Key Directories

- **\`/\`** - Root directory, the top of the file system
- **\`/home\`** - User home directories (\`/home/username\`)
- **\`/root\`** - Home directory for the root user
- **\`/etc\`** - System configuration files
- **\`/var\`** - Variable data (logs, databases, web content)
- **\`/tmp\`** - Temporary files (cleared on reboot)
- **\`/usr\`** - User programs and data
- **\`/bin\`** - Essential command binaries
- **\`/sbin\`** - System binaries (admin commands)
- **\`/dev\`** - Device files
- **\`/proc\`** - Process and system information

## Essential Navigation Commands

### \`pwd\` - Print Working Directory
Shows your current location in the file system.

\`\`\`bash
$ pwd
/home/analyst
\`\`\`

### \`cd\` - Change Directory
Navigate between directories.

\`\`\`bash
cd /var/log        # Absolute path
cd ../             # Go up one level
cd ~               # Go to home directory
cd -               # Go to previous directory
\`\`\`

### \`ls\` - List Directory Contents
Display files and directories.

\`\`\`bash
ls                 # List current directory
ls -l              # Long format (detailed)
ls -la             # Include hidden files
ls -lh             # Human-readable sizes
ls -lt             # Sort by modification time
\`\`\`

### Path Types

**Absolute Path:** Starts from root (\`/\`)
\`\`\`bash
cd /var/log/apache2
\`\`\`

**Relative Path:** Relative to current location
\`\`\`bash
cd logs/apache2
\`\`\`

## Practical Security Examples

**Viewing system logs:**
\`\`\`bash
cd /var/log
ls -lh *.log
\`\`\`

**Checking user directories:**
\`\`\`bash
ls -la /home
\`\`\`

**Finding configuration files:**
\`\`\`bash
ls /etc/ssh
\`\`\`

## Pro Tips

- Use **Tab completion** to auto-complete paths
- Use **\`ls -R\`** to list recursively
- Hidden files start with a dot (.\`)
- \`\`..\`\` means parent directory
- \`\`.\`\` means current directory`;

        await db.query(
            'INSERT INTO lesson_content (task_id, content, content_type, reading_time_minutes) VALUES (?, ?, ?, ?)',
            [6, task6Content, 'markdown', 8]
        );
        console.log('✓ Added lesson content for Task 6: Navigating the File System');

        const task6Questions = [
            ['What command shows your current directory location?', 'pwd', 1, 'Print Working Directory', 0],
            ['What symbol represents the root directory?', '/', 2, 'The top of the file system', 0],
            ['Which directory contains system configuration files?', '/etc', 3, 'Configuration files location', 0],
            ['What command is used to change directories?', 'cd', 4, 'Change Directory', 0],
            ['What does the tilde (~) represent in Linux paths?', 'home directory', 5, 'User home shortcut', 0]
        ];

        for (const q of task6Questions) {
            await db.query(
                'INSERT INTO lesson_questions (task_id, question_text, correct_answer, question_order, hint, case_sensitive) VALUES (6, ?, ?, ?, ?, ?)',
                q
            );
        }
        console.log('✓ Added 5 questions for Task 6\n');

        // Task 7: File Manipulation
        const task7Content = `# File Manipulation in Linux

File manipulation is a core skill for SOC analysts. You'll need to copy logs, create reports, move suspicious files to quarantine, and more.

## Creating Files and Directories

### \`touch\` - Create Empty Files
\`\`\`bash
touch report.txt
touch file1.txt file2.txt file3.txt
\`\`\`

### \`mkdir\` - Make Directory
\`\`\`bash
mkdir案investigations
mkdir -p cases/2024/january    # Create parent directories
\`\`\`

## Copying and Moving

### \`cp\` - Copy Files
\`\`\`bash
cp file.txt backup.txt
cp -r directory/ backup/        # Copy directory recursively
cp *.log /backup/                # Copy multiple files
\`\`\`

### \`mv\` - Move/Rename Files
\`\`\`bash
mv oldname.txt newname.txt      # Rename
mv file.txt /tmp/                # Move
mv *.txt documents/              # Move multiple files
\`\`\`

## Removing Files

### \`rm\` - Remove Files
\`\`\`bash
rm file.txt
rm -r directory/                 # Remove directory
rm -f file.txt                   # Force remove
rm -rf folder/                   # Force recursive (DANGEROUS!)
\`\`\`

⚠️ **WARNING:** \`rm -rf\` is irreversible! Always double-check before running.

## Viewing File Contents

### \`cat\` - Display Entire File
\`\`\`bash
cat access.log
\`\`\`

### \`head\` - First Lines
\`\`\`bash
head -n 20 error.log            # First 20 lines
\`\`\`

### \`tail\` - Last Lines
\`\`\`bash
tail -n 50 system.log
tail -f live.log                 # Follow (real-time)
\`\`\`

### \`less\` - Paginated Viewing
\`\`\`bash
less large_file.log             # Navigate with arrows, q to quit
\`\`\`

## Security Use Cases

**Preserving evidence:**
\`\`\`bash
cp -r /var/log/ /evidence/$(date +%Y%m%d)/
\`\`\`

**Monitoring live logs:**
\`\`\`bash
tail -f /var/log/auth.log
\`\`\`

**Quick file inspection:**
\`\`\`bash
head -n 100 suspicious_script.sh
\`\`\``;

        await db.query(
            'INSERT INTO lesson_content (task_id, content, content_type, reading_time_minutes) VALUES (?, ?, ?, ?)',
            [7, task7Content, 'markdown', 10]
        );
        console.log('✓ Added lesson content for Task 7: File Manipulation');

        const task7Questions = [
            ['What command creates an empty file?', 'touch', 1, 'Makes a new file', 0],
            ['Which command copies files in Linux?', 'cp', 2, 'Copy command', 0],
            ['What flag is needed to copy directories recursively?', '-r', 3, 'Recursive flag', 0],
            ['Which command follows a log file in real-time?', 'tail -f', 4, 'Combines tail with follow', 0],
            ['What command is used to rename a file?', 'mv', 5, 'Move/rename command', 0]
        ];

        for (const q of task7Questions) {
            await db.query(
                'INSERT INTO lesson_questions (task_id, question_text, correct_answer, question_order, hint, case_sensitive) VALUES (7, ?, ?, ?, ?, ?)',
                q
            );
        }
        console.log('✓ Added 5 questions for Task 7\n');

        // Task 8: Understanding Permissions
        const task8Content = `# Linux File Permissions

Understanding Linux permissions is critical for security. Misconfigurations can lead to privilege escalation, unauthorized access, and data breaches.

## Permission Types

Every file has three permission sets:
- **Owner** (u) - The file's owner
- **Group** (g) - Users in the file's group
- **Others** (o) - Everyone else

Each set has three permissions:
- **Read** (r) - 4
- **Write** (w) - 2
- **Execute** (x) - 1

## Reading Permissions

\`\`\`bash
$ ls -l script.sh
-rwxr-xr-- 1 analyst security 1024 Dec 25 10:00 script.sh
\`\`\`

Breaking down \`-rwxr-xr--\`:
- \`-\` - File type (- = file, d = directory)
- \`rwx\` - Owner can read, write, execute
- \`r-x\` - Group can read and execute
- \`r--\` - Others can only read

## Numeric Permissions

Permissions are often expressed as numbers:
- **7** (rwx) = 4+2+1
- **6** (rw-) = 4+2
- **5** (r-x) = 4+1
- **4** (r--) = 4
- **0** (---) = 0

Common examples:
- **755** - Owner: rwx, Group: r-x, Others: r-x
- **644** - Owner: rw-, Group: r--, Others: r--
- **600** - Owner: rw-, Group: ---, Others: ---

## Changing Permissions

### \`chmod\` - Change Mode
\`\`\`bash
chmod 755 script.sh             # Numeric
chmod u+x script.sh             # Add execute for owner
chmod go-w file.txt             # Remove write for group/others
chmod a+r document.txt          # Add read for all
\`\`\`

### \`chown\` - Change Owner
\`\`\`bash
sudo chown analyst file.txt
sudo chown analyst:security file.txt
\`\`\`

### \`chgrp\` - Change Group
\`\`\`bash
sudo chgrp security file.txt
\`\`\`

## Security Implications

**Insecure:**
\`\`\`bash
chmod 777 sensitive.txt         # Anyone can read/write/execute!
\`\`\`

**Secure:**
\`\`\`bash
chmod 600 private_key.pem       # Only owner can read/write
chmod 700 ~/.ssh                 # Only owner can access
\`\`\`

## Special Permissions

- **SUID** (4000) - Run as file owner
- **SGID** (2000) - Run as file group
- **Sticky Bit** (1000) - Only owner can delete

## Checking for Misconfigurations

Find world-writable files (security risk):
\`\`\`bash
find / -type f -perm -002 2>/dev/null
\`\`\`

Find SUID binaries:
\`\`\`bash
find / -perm -4000 2>/dev/null
\`\`\``;

        await db.query(
            'INSERT INTO lesson_content (task_id, content, content_type, reading_time_minutes) VALUES (?, ?, ?, ?)',
            [8, task8Content, 'markdown', 12]
        );
        console.log('✓ Added lesson content for Task 8: Understanding Permissions');

        const task8Questions = [
            ['What does the "r" permission allow?', 'read', 1, 'View file contents', 0],
            ['What numeric value represents full permissions (rwx)?', '7', 2, '4+2+1', 0],
            ['Which command changes file permissions?', 'chmod', 3, 'Change mode', 0],
            ['What permissions are represented by 644?', 'rw-r--r--', 4, 'Owner read/write, others read-only', 0],
            ['What command changes file ownership?', 'chown', 5, 'Change owner', 0]
        ];

        for (const q of task8Questions) {
            await db.query(
                'INSERT INTO lesson_questions (task_id, question_text, correct_answer, question_order, hint, case_sensitive) VALUES (8, ?, ?, ?, ?, ?)',
                q
            );
        }
        console.log('✓ Added 5 questions for Task 8\n');

        // Task 9: Searching and Finding Files
        const task9Content = `# Searching and Finding Files

As a SOC analyst, you'll frequently need to locate files, search for indicators of compromise (IOCs), and hunt for suspicious files across the system.

## The \`find\` Command

The most powerful file search tool in Linux.

### Basic Syntax
\`\`\`bash
find [path] [options] [expression]
\`\`\`

### Finding by Name
\`\`\`bash
find / -name "*.log"
find /home -name "suspicious.sh"
find . -iname "*.TXT"              # Case-insensitive
\`\`\`

### Finding by Type
\`\`\`bash
find /var -type f                  # Files only
find /etc -type d                  # Directories only
find /tmp -type l                  # Symbolic links
\`\`\`

### Finding by Size
\`\`\`bash
find / -size +100M                 # Larger than 100MB
find /home -size -1k               # Smaller than 1KB
find . -size 50M                   # Exactly 50MB
\`\`\`

### Finding by Time
\`\`\`bash
find /var/log -mtime -7            # Modified in last 7 days
find /tmp -atime +30               # Accessed more than 30 days ago
find . -mmin -60                   # Modified in last 60 minutes
\`\`\`

### Finding by Permissions
\`\`\`bash
find / -perm 777                   # Exactly 777
find / -perm -4000                 # SUID files
find /home -perm /222              # Any write permission
\`\`\`

## Executing Commands on Results

### Delete Found Files
\`\`\`bash
find /tmp -name "*.tmp" -delete
\`\`\`

### Execute Command on Each File
\`\`\`bash
find . -name "*.log" -exec gzip {} \\;
find / -name "malware.sh" -exec rm -f {} \\;
\`\`\`

## The \`locate\` Command

Faster than find, uses a database.

\`\`\`bash
locate passwd
locate -i config.conf              # Case-insensitive
updatedb                            # Update database (requires sudo)
\`\`\`

## Security Use Cases

**Find recently modified files:**
\`\`\`bash
find /etc -type f -mtime -1
\`\`\`

**Locate SUID binaries (privilege escalation vectors):**
\`\`\`bash
find / -perm -4000 -type f 2>/dev/null
\`\`\`

**Find world-writable directories:**
\`\`\`bash
find / -type d -perm -002 2>/dev/null
\`\`\`

**Find files owned by specific user:**
\`\`\`bash
find / -user hacker 2>/dev/null
\`\`\`

**Hunt for backdoors in web directories:**
\`\`\`bash
find /var/www -name "*.php" -mtime -7
\`\`\`

## Combining with Other Tools

\`\`\`bash
find /var/log -name "*.log" | xargs grep "Failed password"
\`\`\``;

        await db.query(
            'INSERT INTO lesson_content (task_id, content, content_type, reading_time_minutes) VALUES (?, ?, ?, ?)',
            [9, task9Content, 'markdown', 10]
        );
        console.log('✓ Added lesson content for Task 9: Searching and Finding Files');

        const task9Questions = [
            ['What command is used to search for files in Linux?', 'find', 1, 'The primary search command', 0],
            ['What flag finds files modified in the last 7 days?', '-mtime -7', 2, 'Modified time option', 0],
            ['Which command uses a database for faster file searches?', 'locate', 3, 'Database-based search', 0],
            ['What permission mode represents SUID files?', '-4000', 4, 'Special permission bit', 0],
            ['What option finds files larger than 100MB?', '-size +100M', 5, 'Size greater than', 0]
        ];

        for (const q of task9Questions) {
            await db.query(
                'INSERT INTO lesson_questions (task_id, question_text, correct_answer, question_order, hint, case_sensitive) VALUES (9, ?, ?, ?, ?, ?)',
                q
            );
        }
        console.log('✓ Added 5 questions for Task 9\n');

        // Continuing with remaining tasks...
        console.log('\n✅ Module 2 lessons (Tasks 6-9) seeded successfully!');
        console.log('Note: Tasks 10-13 will be added in the next batch.\n');
        process.exit(0);
    } catch (error) {
        console.error('Error seeding Module 2 lessons:', error);
        process.exit(1);
    }
}

seedModule2Lessons();
