import {test} from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs/promises';
import path from 'node:path';
import os from 'node:os';
import http from 'node:http';
import net from 'node:net';
import {execFile} from 'node:child_process';
import {promisify} from 'node:util';
import {prepareInstall,saveInstall,parseArgs,probeBpq} from './install.mjs';
import {parseConfig} from './config.mjs';
const run=promisify(execFile),probe=async()=>{};
const cfg=(driver='VARA',call='N9DEMO')=>`NODECALL = ${call}-7
NODEALIAS=DEMO
LOCATOR=IO91AA
PORT
PORTNUM=3
ID=HF modem
DRIVER = ${driver}
ENDPORT
PORT
PORTNUM=7
DRIVER = Telnet.dll
HTTPPORT = 8088
TCPPORT=9000
CMS=1
USER=admin,fixture-secret,${call},sysop
USER=operator,another-fixture,${call}-1,sysop
ENDPORT
APPLICATION 1, bbs, ,${call}-11,MAIL
`;
async function fixture(t,driver='VARA'){
const dir=await fs.mkdtemp(path.join(os.tmpdir(),"bpq install O'Brien "));t.after(()=>fs.rm(dir,{recursive:true,force:true}));const root=path.join(dir,'station');await fs.mkdir(path.join(root,'BPQMailChat'),{recursive:true});await fs.writeFile(path.join(root,'BPQ32.cfg'),cfg(driver));await fs.writeFile(path.join(root,'BPQMailChat','BPQMail.cfg'),'BBSForwarding : {\n CMS2 : { ConnectScript="RMS"; Enabled=1; }\n N1PEER : { ConnectScript="ATTACH 3|C N1PEER"; Enabled=1; }\n}\nBBSUsers : {}');
return {dir,root,options:{bpqRoot:root,configPath:path.join(dir,'console.config.json')}};
}
test('configuration ignores banners and comments, accepts whitespace, DLL drivers and Telnet-specific ports',()=>{
const parsed=parseConfig('/* single line comment */\nINFOMSG:\nNODECALL=N0WRONG\nUSER=wrong,not-a-secret,N0WRONG,sysop\n***\n'+cfg('ARDOP')+'\nPORT\nDRIVER=OTHER\nHTTPPORT=9999\nTCPPORT=9998\nENDPORT');
assert.equal(parsed.nodeCall,'N9DEMO-7');assert.equal(parsed.users.length,2);assert.equal(parsed.httpPort,8088);assert.equal(parsed.telnetPort,9000);assert.equal(parsed.apps[0].command,'BBS');assert.equal(parsed.radioPorts[0].driver,'ARDOP');assert.equal(parsed.radioPorts.length,2);
const short=parseConfig('APPLICATION 1,bbs\nAPPLICATION 2,CHAT/TALK,,N9DEMO-12');assert.equal(short.apps[0].command,'BBS');assert.equal(short.apps[0].call,'');assert.equal(short.apps[1].command,'CHAT');assert.equal(short.apps[1].call,'N9DEMO-12');
});
test('fresh install detects profiles and modem without copying credentials or enabling CAT',async t=>{
const f=await fixture(t),plan=await prepareInstall(f.options,{probe});assert.equal(plan.config.radioPort,3);assert.equal(plan.config.winlinkRadio.catControl,false);assert.equal(plan.report.terminal,true);assert.deepEqual(plan.report.forwardProfiles,['CMS2','N1PEER']);assert.ok(!JSON.stringify(plan).includes('fixture-secret'));assert.equal((await saveInstall(plan)).changed,true);assert.ok(!await fs.readFile(plan.configPath,'utf8').then(s=>s.includes('fixture-secret')));
});
test('reinstallation preserves custom settings, backs up once and is idempotent',async t=>{
const f=await fixture(t),saved={bpqRoot:f.root,port:18099,httpPort:8088,radioPort:3,radioDriver:'VARA',sysopUser:'operator',cmsPeer:'CMS2',forwardPeer:'N1PEER',varaSyslogPort:19001,varaLogPath:'D:/Radio/VARAHF.log',winlinkRadio:{catControl:true},customOption:{theme:'dark'}};await fs.writeFile(f.options.configPath,JSON.stringify(saved));
const p=await prepareInstall(f.options,{probe});assert.equal(p.config.port,18099);assert.equal(p.config.sysopUser,'operator');assert.equal(p.config.cmsPeer,'CMS2');assert.equal(p.config.winlinkRadio.catControl,true);assert.equal(p.config.varaSyslogPort,19001);assert.deepEqual(p.config.customOption,saved.customOption);const result=await saveInstall(p);assert.deepEqual(JSON.parse(await fs.readFile(result.backup,'utf8')),saved);const again=await prepareInstall(f.options,{probe});assert.equal((await saveInstall(again)).changed,false);
});
test('a different station and changed modem do not inherit CAT, peers or VARA paths',async t=>{
const f=await fixture(t);await fs.writeFile(f.options.configPath,JSON.stringify({bpqRoot:f.root,radioPort:3,radioDriver:'VARA',sysopUser:'operator',cmsPeer:'CMS2',forwardPeer:'N1PEER',varaLogPath:'D:/old/VARAHF.log',winlinkRadio:{catControl:true}}));
await fs.writeFile(path.join(f.root,'BPQ32.cfg'),cfg('SCSPACTOR'));const changed=await prepareInstall(f.options,{probe});assert.equal(changed.config.winlinkRadio.catControl,false);assert.equal(changed.config.varaLogPath,null);
const root=path.join(f.dir,'another station');await fs.mkdir(root);await fs.writeFile(path.join(root,'BPQ32.cfg'),cfg('ARDOP','N8OTHER'));const other=await prepareInstall({...f.options,bpqRoot:root},{probe});assert.equal(other.config.sysopUser,'admin');assert.equal(other.config.forwardPeer,'');assert.equal(other.config.cmsPeer,'RMS');assert.equal(other.config.winlinkRadio.catControl,false);assert.equal(other.config.varaLogPath,null);
});
test('Telnet-only and non-VARA stations install with absent services and no fake modem',async t=>{
const f=await fixture(t);await fs.writeFile(path.join(f.root,'BPQ32.cfg'),cfg().replace(/PORT\nPORTNUM=3[\s\S]*?ENDPORT\n/,'').replace(/^APPLICATION.*$/m,''));await fs.rm(path.join(f.root,'BPQMailChat'),{recursive:true,force:true});const p=await prepareInstall(f.options,{probe});assert.equal(p.config.radioPort,null);assert.equal(p.config.varaLogPath,null);assert.equal(p.config.winlinkRadio.catControl,false);assert.deepEqual(p.report.forwardProfiles,[]);
for(const driver of ['SCSPACTOR','ARDOP','KISS']){await fs.writeFile(path.join(f.root,'BPQ32.cfg'),cfg(driver));const p=await prepareInstall(f.options,{probe});assert.equal(p.config.radioDriver,driver);assert.equal(p.config.varaLogPath,null);}
await assert.rejects(prepareInstall({...f.options,catControl:true},{probe}),/modem HF/);
});
test('invalid ports, users, profiles and local JSON fail without overwriting settings',async t=>{
const f=await fixture(t);for(const options of [{port:8088},{httpPort:70000},{httpPort:0},{port:1},{radioPort:99},{sysopUser:'missing'},{forwardPeer:'MISSING'},{cmsPeer:'MISSING'}])await assert.rejects(prepareInstall({...f.options,...options},{probe}));
for(const value of ['{bad json','null','[]']){await fs.writeFile(f.options.configPath,value);await assert.rejects(prepareInstall(f.options,{probe}),/JSON/);assert.equal(await fs.readFile(f.options.configPath,'utf8'),value);}
});
test('offline BPQ and failed checks never create local configuration',async t=>{
const f=await fixture(t);await assert.rejects(prepareInstall(f.options,{probe:async()=>{throw new Error('BPQ offline');}}),/offline/);await assert.rejects(fs.stat(f.options.configPath),{code:'ENOENT'});
});
test('HTTP check recognises BPQ and rejects an unrelated web service',async t=>{
let real=false;const server=http.createServer((req,res)=>res.end(real?'BPQ Ports':'Unrelated ports page'));await new Promise(r=>server.listen(0,'127.0.0.1',r));t.after(()=>new Promise(r=>server.close(r)));await assert.rejects(probeBpq(server.address().port),/non conferma/);real=true;await probeBpq(server.address().port);
});
test('CLI parses explicit options and rejects typos or missing values',()=>{
assert.deepEqual(parseArgs(['--port','8099','--enable-radio-cat','--check-only']),{port:'8099',catControl:true,checkOnly:true});assert.throws(()=>parseArgs(['--port']));assert.throws(()=>parseArgs(['--unknown','x']));assert.throws(()=>parseArgs(['--enable-radio-cat','--disable-radio-cat']));
});
test('PowerShell installer CheckOnly supports paths with spaces and skips startup, task and firewall', {skip:process.platform!=='win32'},async t=>{
const f=await fixture(t);const fake=http.createServer((req,res)=>res.end('BPQ Ports'));await new Promise(r=>fake.listen(0,'127.0.0.1',r));t.after(()=>new Promise(r=>fake.close(r)));await fs.writeFile(path.join(f.root,'BPQ32.cfg'),cfg().replace('8088',String(fake.address().port)));
const env={...process.env,BPQ_CONSOLE_CONFIG:f.options.configPath};delete env.BPQ_ROOT;delete env.BPQ_CONSOLE_PORT;
const result=await run('powershell.exe',['-NoProfile','-NonInteractive','-ExecutionPolicy','RemoteSigned','-File',path.resolve('Install.ps1'),'-NodeExe',process.execPath,'-BpqRoot',f.root,'-CheckOnly','-AutoStart','-EnableLAN','-Restart','-RadioPort','3','-SysopUser','operator','-Language','en','-ForwardPeer','N1PEER','-CmsPeer','CMS2'],{env,windowsHide:true,timeout:20000});assert.match(result.stdout,/N9DEMO-7/);const report=JSON.parse(result.stdout);assert.equal(report.selectedRadio,3);assert.equal(report.sysopUser,'operator');assert.ok(!result.stdout.includes('fixture-secret'));await assert.rejects(fs.stat(f.options.configPath),{code:'ENOENT'});
});
const freePort=async()=>{const s=net.createServer();await new Promise(r=>s.listen(0,'127.0.0.1',r));const p=s.address().port;await new Promise(r=>s.close(r));return p;};
test('PowerShell startup confirms readiness, handles duplicate starts, restart and failed startup', {skip:process.platform!=='win32'},async t=>{
const f=await fixture(t),script=path.join(f.dir,'Start-Console.ps1');await fs.copyFile('Start-Console.ps1',script);const configFile=path.join(f.dir,'console.config.json');let pid=null;t.after(()=>{if(pid)try{process.kill(pid);}catch{}});
const source="import http from 'node:http';import fs from 'node:fs';const c=JSON.parse(fs.readFileSync('console.config.json','utf8'));http.createServer((q,r)=>{r.setHeader('Content-Type','application/json');r.end(JSON.stringify({service:'bpq-console',pid:process.pid}));}).listen(c.port,'127.0.0.1');";await fs.writeFile(path.join(f.dir,'server.mjs'),source);let port=await freePort();await fs.writeFile(configFile,JSON.stringify({port,nodeExe:process.execPath}));const env={...process.env};delete env.BPQ_CONSOLE_CONFIG;delete env.BPQ_CONSOLE_PORT;delete env.BPQ_ROOT;
const start=extra=>run('powershell.exe',['-NoProfile','-NonInteractive','-ExecutionPolicy','RemoteSigned','-File',script,...extra],{env,windowsHide:true,timeout:25000});assert.match((await start([])).stdout,/avviato/);pid=(await(await fetch('http://127.0.0.1:'+port+'/health')).json()).pid;assert.match((await start([])).stdout,/gia in esecuzione/);
const unrelated=net.createServer();await new Promise(r=>unrelated.listen(0,'127.0.0.1',r));try{await fs.writeFile(configFile,JSON.stringify({port:unrelated.address().port,nodeExe:process.execPath}));await assert.rejects(start(['-Restart']));assert.equal((await(await fetch('http://127.0.0.1:'+port+'/health')).json()).pid,pid);}finally{await new Promise(r=>unrelated.close(r));}
port=await freePort();await fs.writeFile(configFile,JSON.stringify({port,nodeExe:process.execPath}));await assert.rejects(start([]));assert.match((await start(['-Restart'])).stdout,/avviato/);pid=(await(await fetch('http://127.0.0.1:'+port+'/health')).json()).pid;
await fs.writeFile(path.join(f.dir,'server.mjs'),"throw new Error('fixture startup failure');");await assert.rejects(start(['-Restart']));pid=null;assert.match(await fs.readFile(path.join(f.dir,'server-error.log'),'utf8'),/fixture startup failure/);
});
test('installer language defaults can be selected, preserved and validated',async t=>{
const f=await fixture(t);const plan=await prepareInstall({...f.options,language:'en'},{probe});assert.equal(plan.config.language,'en');await saveInstall(plan);assert.equal((await prepareInstall(f.options,{probe})).config.language,'en');assert.equal((await prepareInstall({...f.options,language:'it'},{probe})).config.language,'it');await assert.rejects(prepareInstall({...f.options,language:'fr'},{probe}),/language/);assert.equal(parseArgs(['--language','en']).language,'en');
});
test('installer preserves the sysop allow-list for the same station, validates it and clears it for a different station',async t=>{
const f=await fixture(t),saved={bpqRoot:f.root,sysopUser:'admin',sysopUsers:['OPERATOR']};
await fs.writeFile(f.options.configPath,JSON.stringify(saved));
const plan=await prepareInstall(f.options,{probe});assert.deepEqual(plan.config.sysopUsers,['OPERATOR']);await saveInstall(plan);
assert.equal((await saveInstall(await prepareInstall(f.options,{probe}))).changed,false);
await fs.writeFile(f.options.configPath,JSON.stringify({...saved,sysopUsers:['missing']}));await assert.rejects(prepareInstall(f.options,{probe}),/sysopUsers/);
const other=path.join(f.dir,'other-station');await fs.mkdir(other);await fs.writeFile(path.join(other,'BPQ32.cfg'),cfg('ARDOP','N8OTHER'));
assert.equal((await prepareInstall({...f.options,bpqRoot:other},{probe})).config.sysopUsers,undefined);
});