59 lines
7.3 KiB
JavaScript
59 lines
7.3 KiB
JavaScript
import {readFile,writeFile,copyFile,rename} from 'node:fs/promises';
|
||
import http from 'node:http';
|
||
import path from 'node:path';
|
||
import os from 'node:os';
|
||
import {fileURLToPath} from 'node:url';
|
||
import {parseConfig,validPort} from './config.mjs';
|
||
import {parseForwarding} from './forwarding.mjs';
|
||
import {modemFamily} from './winlink-gateways.mjs';
|
||
|
||
const dir=path.dirname(fileURLToPath(import.meta.url));
|
||
export async function readLocalConfig(file){try{const value=JSON.parse(await readFile(file,'utf8'));if(!value||typeof value!=='object'||Array.isArray(value))throw new Error('Object required');return value;}catch(e){if(e.code==='ENOENT')return {};throw new Error('Configurazione locale non leggibile: correggere il JSON prima di reinstallare');}}
|
||
export function probeBpq(port){return new Promise((resolve,reject)=>{
|
||
const request=http.get({hostname:'127.0.0.1',port,path:'/Node/Ports.html',headers:{Connection:'close'},agent:false},response=>{let text='';response.on('data',b=>{text+=b;if(text.length>2e6)response.destroy(new Error('Risposta HTTP troppo grande'));});response.on('error',reject);response.on('end',()=>response.statusCode===200&&/\/Node\//i.test(text)&&/\bPorts\b/i.test(text)?resolve():reject(new Error('Il server HTTP non conferma BPQ')));});
|
||
request.setTimeout(8000,()=>request.destroy(new Error('Timeout BPQ')));request.on('error',()=>reject(new Error('BPQ non raggiungibile: avviare BPQ e verificare HTTPPORT')));
|
||
});}
|
||
const samePath=(a,b)=>process.platform==='win32'?path.resolve(a).toLowerCase()===path.resolve(b).toLowerCase():path.resolve(a)===path.resolve(b);
|
||
export async function prepareInstall(options={},dependencies={}){
|
||
const configPath=path.resolve(options.configPath||process.env.BPQ_CONSOLE_CONFIG||path.join(dir,'console.config.json'));
|
||
const previous=await readLocalConfig(configPath);
|
||
const root=path.resolve(options.bpqRoot||process.env.BPQ_ROOT||previous.bpqRoot||path.join(process.env.APPDATA||path.join(os.homedir(),'AppData','Roaming'),'BPQ32'));
|
||
const detected=parseConfig(await readFile(path.join(root,'BPQ32.cfg'),'utf8'));
|
||
if(!detected.nodeCall)throw new Error('NODECALL non rilevato in BPQ32.cfg');
|
||
if(!detected.users.length)throw new Error('Configurare un USER Telnet sysop in BPQ32.cfg');
|
||
const sameStation=Boolean(previous.bpqRoot&&samePath(previous.bpqRoot,root)),saved=sameStation?previous:{};
|
||
const port=Number(options.port??process.env.BPQ_CONSOLE_PORT??previous.port??8090),httpPort=Number(options.httpPort??saved.httpPort??detected.httpPort);
|
||
if(!validPort(port,1024)||!validPort(httpPort)||port===httpPort)throw new Error('Porte non valide o in conflitto: pannello 1024-65535, HTTP BPQ 1-65535, diverse fra loro');
|
||
const chosen=options.radioPort??saved.radioPort??detected.radioPorts[0]?.id??null;
|
||
const radio=chosen==null?null:detected.radioPorts.find(p=>p.id===Number(chosen));
|
||
if(chosen!=null&&!radio)throw new Error('Porta radio selezionata non rilevata: specificare -RadioPort');
|
||
const sysopUser=options.sysopUser??saved.sysopUser??detected.users[0].user;
|
||
if(!detected.users.some(u=>u.user===sysopUser))throw new Error('Utente sysop non rilevato: specificare -SysopUser');
|
||
let profiles=[];try{profiles=parseForwarding(await readFile(path.join(root,'BPQMailChat','BPQMail.cfg'),'utf8'),detected.ports);}catch(e){if(e.code!=='ENOENT')throw e;}
|
||
const peers=profiles.map(p=>p.call),forwardPeer=String(options.forwardPeer??saved.forwardPeer??'').toUpperCase(),cmsPeer=String(options.cmsPeer??saved.cmsPeer??'RMS').toUpperCase();
|
||
if(forwardPeer&&!peers.includes(forwardPeer))throw new Error('Profilo forwarding selezionato non rilevato');
|
||
if(!/^[A-Z0-9-]{1,12}$/.test(cmsPeer))throw new Error('Nome profilo CMS non valido');
|
||
if(options.cmsPeer&&!peers.includes(cmsPeer))throw new Error('Profilo CMS selezionato non rilevato');
|
||
const sameRadio=sameStation&&Number(saved.radioPort)===radio?.id&&(!saved.radioDriver||saved.radioDriver===radio.driver);
|
||
const catControl=options.catControl??(sameRadio&&saved.winlinkRadio?.catControl===true);
|
||
if(catControl&&(!radio||!modemFamily(radio.driver)))throw new Error('Winlink radio richiede un modem HF VARA, Pactor o ARDOP');
|
||
const vara=Boolean(radio&&/^VARA/i.test(radio.driver));
|
||
const language=options.language??previous.language??null;if(language!=null&&!['it','en'].includes(language))throw new Error('language deve essere it oppure en');
|
||
const config={...saved,...(language?{language}:{}),nodeExe:process.execPath,bpqRoot:root,httpPort,port,radioPort:radio?.id??null,radioDriver:radio?.driver??null,sysopUser,forwardPeer,cmsPeer,varaSyslogPort:saved.varaSyslogPort??18514,varaLogPath:vara?(options.varaLogPath??(sameRadio?saved.varaLogPath:null)??null):null,winlinkRadio:{...(sameRadio?saved.winlinkRadio:{}),catControl:Boolean(catControl)}};
|
||
if(!validPort(Number(config.varaSyslogPort)))throw new Error('Porta syslog VARA non valida');
|
||
const warnings=[];if(detected.radioPorts.length>1&&options.radioPort==null&&saved.radioPort==null)warnings.push('Più modem rilevati: selezionata la prima porta; usare -RadioPort per cambiarla.');
|
||
if(detected.winlink&&!peers.includes(cmsPeer))warnings.push('Profilo CMS non presente: configurarlo in BPQ prima di usare il sync Winlink.');
|
||
if(options.catControl===true)warnings.push('CAT abilitato su richiesta: verificare RADIO in BPQ prima di una chiamata; nessuna trasmissione eseguita dall’installer.');
|
||
await (dependencies.probe||probeBpq)(httpPort);
|
||
return {config,configPath,previous,report:{bpq:'in esecuzione, HTTP verificato',nodeCall:detected.nodeCall,ports:detected.ports,services:detected.apps.map(a=>a.command),terminal:Boolean(detected.telnetPort),forwardProfiles:peers,selectedRadio:radio?.id??null,sysopUser,warnings}};
|
||
}
|
||
export async function saveInstall(plan){
|
||
if(JSON.stringify(plan.previous)===JSON.stringify(plan.config))return {changed:false};
|
||
let backup=null;try{backup=plan.configPath+'.'+new Date().toISOString().replace(/[:.]/g,'-')+'.backup';await copyFile(plan.configPath,backup);}catch(e){if(e.code!=='ENOENT')throw e;backup=null;}
|
||
await writeFile(plan.configPath+'.tmp',JSON.stringify(plan.config,null,2)+'\n');await rename(plan.configPath+'.tmp',plan.configPath);return {changed:true,backup};
|
||
}
|
||
export function parseArgs(args){const names={'bpq-root':'bpqRoot',port:'port','http-port':'httpPort','radio-port':'radioPort','sysop-user':'sysopUser','forward-peer':'forwardPeer','cms-peer':'cmsPeer','vara-log':'varaLogPath','config-path':'configPath',language:'language'},options={};
|
||
for(let i=0;i<args.length;i++){const n=args[i];if(n==='--check-only'){options.checkOnly=true;continue;}if(n==='--enable-radio-cat'||n==='--disable-radio-cat'){if(options.catControl!==undefined)throw new Error('Specificare una sola opzione CAT');options.catControl=n==='--enable-radio-cat';continue;}const key=names[n.slice(2)];if(!n.startsWith('--')||!key||args[i+1]===undefined||args[i+1].startsWith('--'))throw new Error('Opzione installer non valida o valore mancante');options[key]=args[++i];}return options;
|
||
}
|
||
if(process.argv[1]&&samePath(process.argv[1],fileURLToPath(import.meta.url))){try{const options=parseArgs(process.argv.slice(2)),plan=await prepareInstall(options);console.log(JSON.stringify(plan.report,null,2));if(!options.checkOnly){const saved=await saveInstall(plan);console.log(saved.changed?'Configurazione salvata senza password. Backup precedente: '+(saved.backup||'prima installazione'):'Configurazione invariata.');}}catch(e){console.error('Installazione interrotta: '+e.message);process.exitCode=1;}}
|