#!/usr/bin/env node
// Cross-platform script to set artifact naming based on version

const fs = require('fs');
const path = require('path');
const { spawn } = require('child_process');

// Read the package.json to get the version
const packageJsonPath = path.join(__dirname, '..', 'package.json');
const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
const version = packageJson.version;

console.log(`Current version: ${version}`);

// Determine the artifact suffix based on the version
let artifactSuffix = '';

if (version.includes('alpha')) {
    artifactSuffix = `alpha-${version}-`;
    console.log(`Detected alpha version, setting suffix to: ${artifactSuffix}`);
} else if (version.includes('beta')) {
    artifactSuffix = `beta-${version}-`;
    console.log(`Detected beta version, setting suffix to: ${artifactSuffix}`);
} else {
    artifactSuffix = '';
    console.log('Detected release version, no suffix will be added');
}

// Set the environment variable for the current process
process.env.ARTIFACT_SUFFIX = artifactSuffix;

console.log(`ARTIFACT_SUFFIX set to: '${artifactSuffix}'`);

// If arguments are passed, execute the remaining command with the environment variable set
if (process.argv.length > 2) {
    const command = process.argv[2];
    const args = process.argv.slice(3);
    
    console.log(`Executing: ${command} ${args.join(' ')}`);
    
    const child = spawn(command, args, {
        stdio: 'inherit',
        env: { ...process.env, ARTIFACT_SUFFIX: artifactSuffix },
        shell: true
    });
    
    child.on('close', (code) => {
        process.exit(code);
    });
} else {
    // Just setting the environment variable
    console.log('Environment variable set. Use this script with additional arguments to run commands with the variable set.');
}
