document.addEventListener("DOMContentLoaded", () => { const username = localStorage.getItem("username"); if (!username) { alert("You need to log in first."); window.location.href = "/"; return; } const terminal = document.getElementById("terminal"); const commandInput = document.getElementById("command"); const appendToTerminal = (text, type = "info") => { const line = document.createElement("div"); line.textContent = text; // Differentiate logs visually (e.g., errors in red) if (type === "error") { line.style.color = "red"; } else if (type === "warn") { line.style.color = "orange"; } else { line.style.color = "white"; } terminal.appendChild(line); terminal.scrollTop = terminal.scrollHeight; }; const fetchLogs = async () => { try { const response = await fetch(`/logs?username=${username}`); if (response.ok) { const logs = await response.text(); terminal.innerHTML = ""; logs.split("\n").forEach((line) => { if (line.includes("WARN")) { appendToTerminal(line, "warn"); } else if (line.includes("ERROR") || line.includes("error")) { appendToTerminal(line, "error"); } else if (line.trim()) { appendToTerminal(line); } }); } else { appendToTerminal("Failed to fetch logs.", "error"); } } catch (error) { appendToTerminal("Error fetching logs.", "error"); } }; const sendCommand = async (command) => { appendToTerminal(`$ ${command}`); try { const response = await fetch("/execute", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ username, command }), }); if (response.ok) { fetchLogs(); } else { appendToTerminal("Error executing command.", "error"); } } catch (error) { appendToTerminal("Command execution failed.", "error"); } }; document.getElementById("send").addEventListener("click", () => { const command = commandInput.value.trim(); if (command) { sendCommand(command); commandInput.value = ""; } }); document.getElementById("start").addEventListener("click", () => { sendCommand("yarn install && yarn start"); }); document.getElementById("stop").addEventListener("click", () => { sendCommand("pkill -f node"); }); document.getElementById("restart").addEventListener("click", () => { sendCommand("pkill -f node && yarn start"); }); document.getElementById("deploy").addEventListener("click", async () => { const repoUrl = prompt("Enter the GitHub repository URL to deploy:"); if (repoUrl) { try { const response = await fetch("/deploy", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ username, repoUrl }), }); if (response.ok) { appendToTerminal("Deployment started..."); fetchLogs(); } else { appendToTerminal("Error starting deployment.", "error"); } } catch (error) { appendToTerminal("Deployment failed.", "error"); } } }); // Fetch logs on load fetchLogs(); });