// VBBS Script 
// Last edit: 4/15/26 Merged a few into one today.
"use strict";

// === CONFIG: Set your desired BBS install date here ===
var installDateString = "2025-02-15"; // Format: YYYY-MM-DD

// Accurate system wide download counter anyone? - has a check to only update data files once a day so you can leave it in... although maybe your bbs has to many 
// files or is to slow for updating while caller waits...
bbs.exec("?vbbsDownloadCounter.js"); // if you run it on automatically or some other way or dont want this feature comment this out

// === Convert to epoch timestamp ===
var installParts = installDateString.split("-");
var manualInstallDate = new Date(
  parseInt(installParts[0]), // year
  parseInt(installParts[1]) - 1, // month (0-based)
  parseInt(installParts[2]) // day
);
var manualInstallEpoch = Math.floor(manualInstallDate.getTime() / 1000);

// === Get current time and system active time ===
var now = time(); // current epoch seconds
var activeMinutesSinceInstall = system.stats.total_timeon; // in minutes
var activeSeconds = activeMinutesSinceInstall * 60;

// === Compute earliest valid install date based on usage ===
var earliestValidInstallEpoch = now - activeSeconds;

// === Use whichever is earlier: manual or valid ===
var bbsInstallTime = Math.min(manualInstallEpoch, earliestValidInstallEpoch);

// === Log adjusted install date if changed ===
if (bbsInstallTime !== manualInstallEpoch) {
  print(
    "\nWARNING: Manual install date was too recent and has been adjusted to match system activity.");
}

// === Continue with daily and overall stats ===
var nowDate = new Date(now * 1000);
var midnight =
  new Date(
    nowDate.getFullYear(),
    nowDate.getMonth(),
    nowDate.getDate()).getTime() / 1000;

var totalMinutesToday = Math.round((now - midnight) / 60);
var activeMinutesToday = system.stats.timeon_today;
var idleMinutesToday = totalMinutesToday - activeMinutesToday;
if (idleMinutesToday < 0) idleMinutesToday = 0;
var usagePercentToday = Math.round(
  (activeMinutesToday / totalMinutesToday) * 100);

var totalMinutesSinceInstall = Math.round((now - bbsInstallTime) / 60);
var idleMinutesSinceInstall =
  totalMinutesSinceInstall - activeMinutesSinceInstall;
if (idleMinutesSinceInstall < 0) idleMinutesSinceInstall = 0;
var usagePercentSinceInstall = Math.round(
  (activeMinutesSinceInstall / totalMinutesSinceInstall) * 100);

function vbbsDrawLine(length, char) {
  var line = "";
  for (var i = 0; i < length; i++) {
    line += char;
  }
  return line;
}

function loadFileToString(filepath) {
    var file = new File(filepath);
    if(!file.open("r")) {
//        print("Failed to open file: " + filepath);
        return null;
    }
    var content = file.read();
    file.close();
    return content;
}

// usage:

var vzDLCount = loadFileToString(system.data_dir + "download_count.txt");
if(vzDLCount == null) {
    text = "n/a";
}
 vzDLCount = vzDLCount.replace(/[\r\n]+$/g, "");
 
function repeatChar(char, count) {
    var str = "";
    for(var i = 0; i < count; i++) {
        str += char;
    }
    return str;
}

function fixedLength10(str) { //11 seems better
  str = str.toString();
    if (str.length > 11) {
        return str.substring(0, 11);
    } else {
        return str + repeatChar(" ", 11 - str.length);
    }
}


function vbbsShowBBSInfo() {
  // === Output dbug===
  /*
print("\n--- DAILY STATS ---");
print("Current Time:          " + strftime("%Y-%m-%d %H:%M:%S", now));
print("Active Time Today:     " + activeMinutesToday + " minutes");
print("Idle Time Today:       " + idleMinutesToday + " minutes");
print("System Usage Today:    " + usagePercentToday + "%");

print("\n--- SINCE BBS INSTALL ---");
print("Effective Install Date:" + strftime("%Y-%m-%d %H:%M:%S", bbsInstallTime));
print("Active Time Since:     " + Math.round(activeMinutesSinceInstall / 60) + " hours");
print("Idle Time Since:       " + Math.round(idleMinutesSinceInstall  / 60) + " hours");
print("System Usage Overall:  " + usagePercentSinceInstall + "%");
*/
  var vbbsPrivateMailToday =
    system.stats.feedback_sent_today + system.stats.email_sent_today;
  //var vbbsPrivateMailAlltime =
  //  system.stats.total_feedback + system.stats.total_email;

  console.putmsg("\r\n\r\n");
  console.print("\x01h\x01g " + vbbsDrawLine(38, ascii(196)));
  console.print("\n\r\x01n REGISTERED\n\r");
  console.putmsg(" \x01h\x01rThe Virtual BBS/NET Version  \x01b@VER@\n\r");
  console.putmsg("\x01n Channel  \x01h\x01r  @NODE@\x01y  @DATE@  \x01g@TIME@");
  console.putmsg("\r\n\r\n");
  console.putmsg(" Statistics            Total    Today");
  console.print(" \x01h\x01g\r\n " + vbbsDrawLine(38, ascii(196)));
  console.putmsg(
    "\r\n\x01n Calls                \x01h\x01r@TCALLS|L11@\x01y@STATS.LTODAY|L8@");
  console.putmsg(
    "\r\n\x01n Posts                \x01h\x01r@TMSG|L11@\x01y@STATS.PTODAY@");
  console.putmsg(
    "\r\n\x01n Emails               \x01h\x01r" + fixedLength10(system.stats.total_email)+"\x01y"+vbbsPrivateMailToday);
  console.putmsg(
    "\r\n\x01n Downloads            \x01h\x01r" + fixedLength10(vzDLCount)+"\x01y@STATS.DLS@");
  console.putmsg(
    "\r\n\x01n Uploads              \x01h\x01r@TFILE|L11@\x01y@STATS.ULS@");
  console.putmsg(
    "\r\n\x01n Active               \x01h\x01r" + fixedLength10(activeMinutesSinceInstall) + "\x01y" + activeMinutesToday);
  console.putmsg(
    "\r\n\x01n Idle                 \x01h\x01r" + fixedLength10(idleMinutesSinceInstall) +"\x01y" + idleMinutesToday);
  console.putmsg(
    "\r\n\x01n Duty Cycle %         \x01h\x01r" + fixedLength10(usagePercentSinceInstall) + "\x01y" + usagePercentToday);
  console.print(" \x01h\x01g\r\n " + vbbsDrawLine(38, ascii(196)));
  console.putmsg("\x01n\r\n " + system.name + " has been online @UPTIME@");
  console.print(" \x01h\x01g\r\n " + vbbsDrawLine(38, ascii(196)));
  console.print(" \x01h\x01g\r\n " + vbbsDrawLine(38, ascii(196)) + "\r\n");
}

function vbbsLogoff() {
  console.newline(1);
   if(console.yesno("\x01h\x01r Confirm - Log Off? \x01y(\x01bYes\x01y/\x01rNo\x01y/Enter=\x01bYes\x01y)")) {
  console.print("\x01Q");
  //console.printfile(system.text_dir + "menu/"+ vbbsMenuPath + "logoff.msg");
  bbs.menu("vbbsmenu/logoff"); //vbbs logoff menu
  console.print("\x01P");  // put the pause 
  //console.printfile(system.text_dir + "menu/default5/logoff.msg"); //normal logoff menu i dont know what way...
  bbs.menu("logoff"); //normal logoff menu
  bbs.hangup();
  }
}



if (argv.indexOf("-SHOW") == 0)
{
vbbsShowBBSInfo();
}
else if (argv.indexOf("-LOGOFF") == 0)
{
vbbsLogoff();
}