#!/bin/bash
set -e # Exit immediately if a command exits with a non-zero status

echo "--- 1. Updating Repositories ---"
apt-get update -y

echo "--- 2. Installing Nginx and Node.js ---"
apt-get install -y nginx nodejs curl

echo "--- 3. Setting up the Application Directory ---"
mkdir -p /opt/node-app
# Set permissions so our specific user can write to it later
# (For simplicity in this script, we keep root, but in prod use a dedicated user)

echo "--- 4. Creating the Node.js Server File ---"
cat >/opt/node-app/server.js <<EOF
const http = require('http');
const fs = require('fs');
const path = require('path');

const LOG_FILE = path.join(__dirname, 'access.log');
const PORT = 3000;

const server = http.createServer((req, res) => {
    // 1. Log the request to a file
    const logEntry = \`\${new Date().toISOString()} - Request received from \${req.socket.remoteAddress}\n\`;
    
    fs.appendFile(LOG_FILE, logEntry, (err) => {
        if (err) console.error('Error writing to log:', err);
    });

    // 2. Send Response
    res.statusCode = 200;
    res.setHeader('Content-Type', 'text/plain');
    res.end('Hello from the SysAdmin Lab!\n');
});

server.listen(PORT, () => {
    console.log(\`Server running on port \${PORT}\`);
});
EOF

echo "--- Setup Complete! ---"
echo "You can test the app manually with: node /opt/node-app/server.js"
