// Save as: dbaops-env-check.js
const os = require("os");
const fs = require("fs");
const { execSync } = require("child_process");

function section(title) {
  console.log("\n=== " + title + " ===");
}

function run(cmd) {
  try {
    return execSync(cmd, { encoding: "utf8" }).trim();
  } catch {
    return "Not Available";
  }
}

function listPorts() {
  const data = run("netstat -an | findstr LISTENING");
  return data.split("\n").slice(0, 10);
}

function getSQLStatus() {
  return run('sc query "MSSQLSERVER"');
}

function getDotNetInfo() {
  return run('dotnet --info');
}

function getEnvVars() {
  return Object.entries(process.env)
    .filter(([key]) => key.includes("DB") || key.includes("SQL") || key.includes("APP"))
    .map(([k, v]) => `${k}=${v}`);
}

section("SYSTEM INFO");
console.log("OS:", os.type(), os.release());
console.log("Hostname:", os.hostname());
console.log("CPU:", os.cpus()[0].model);
console.log("Cores:", os.cpus().length);
console.log("Memory:", (os.totalmem() / 1e9).toFixed(2) + " GB");

section("NETWORK");
console.log("Interfaces:", Object.values(os.networkInterfaces()).flat().map(i => i.address).join(", "));
console.log("Listening Ports:", listPorts().join("\n"));

section("NODE & NPM");
console.log("Node.js:", process.version);
console.log("NPM:", run("npm -v"));

section("ENVIRONMENT VARIABLES");
console.log(getEnvVars().join("\n") || "No DB-related env vars found");

section("SERVICES");
console.log("SQL Server:", getSQLStatus());
console.log(".NET Info:", getDotNetInfo());

section("DISK");
console.log("Root Directory:", run("dir /a /-C") || "Use Linux `df -h` on Unix systems");

section("DONE ✅");
