import { existsSync } from "jsr:@std/fs/exists";
import { join } from "node:path";
const APPDATA = Deno.env.get('APPDATA');
const Install_PowerShell = () => {
let ps_module_path = Deno.env.get('PSModulePath');
if(!ps_module_path) return false;
ps_module_path = ps_module_path.split(';').find(entry => entry.match(/[\\\/]Documents[\\\/]/));
if(!ps_module_path) return false;
const ps_profile_path = join(ps_module_path, '../', 'Microsoft.PowerShell_profile.ps1');
const profile_append = Deno.readTextFileSync(join(Deno.cwd(), 'lib/cli/commands/install_data', 'profile_append.ps1'));
let profile_contents = '';
try {
profile_contents = Deno.readTextFileSync(ps_profile_path);
} catch(_) { /**/ }
profile_contents = profile_contents.replace(/\s+function Run-Viapak[\s\S]+Set-Alias -Name viapak -Value Run-Viapak\s+/, '\n\n');
if(profile_contents.length) profile_contents += '\n\n';
profile_contents += profile_append;
profile_contents = profile_contents.replace(/^[\n\s]+/, '').replace(/\n{2,}/, '\n').replace(/\n{2,}$/, '\n');
Deno.writeTextFileSync(ps_profile_path, profile_append, {
create: true
})
return true;
}
const InstallCMD = () => {
let PATH = Deno.env.get('PATH');
if(!PATH || !APPDATA) return false; // Something would need to be horribly wrong!
const viapak_path = join(APPDATA, '.viapak');
if(!existsSync(viapak_path)) {
Deno.mkdirSync(viapak_path);
}
if(!PATH.includes(viapak_path)) {
console.log('NOT IN PATH!');
console.log(PATH);
// PATH = PATH.concat(';', viapak_path);
// const result = spawnSync('setx', ['PATH', PATH]);
// // STDOUT
// const stdOut = result.stdout.toString();
// console.log(stdOut);
// // STDERR
// const stdErr = result.stderr.toString();
// if(stdErr === '') {
// ENVIRONMENT_MODIFIED = true;
// } else {
// console.error(`ERROR: ${stdErr}`);
// }
}
const cmd_contents = Deno.readTextFileSync(join(Deno.cwd(), 'lib/cli/commands/install_data', 'viapak.cmd'));
Deno.writeTextFileSync(join(viapak_path, 'viapak.cmd'), cmd_contents);
return false;
}
let ENVIRONMENT_MODIFIED = false;
const powershell = Install_PowerShell();
const cmd = InstallCMD();
export {
powershell,
cmd,
}