/**
 * 执行脚本环境要求
 * 1. aliyun cli
 * 2. docker
 */

const { execSync } = require('child_process');
const { argv, platform } = require('process');

const imageName = argv[2];
const tag = argv[3];
const url = 'production-legolas-registry.ap-northeast-1.cr.aliyuncs.com';
const repositories = `${url}/blacklagoon/heijiao-server`;

function executeCommand(command) {
    try {
        const outPut = execSync(command, { stdio: 'inherit' });
        return outPut?.toString() || '';
    } catch (error) {
        console.error(`Command execution failed: ${command}`)
        console.error(error.message);
        process.exit();
    }
}

function buildImage() {
    console.log('构建镜像');
    if (platform == 'linux') executeCommand(`npm run build_docker_linux`);
    else if (platform == 'win32') executeCommand(`npm run build_docker_win`)
    executeCommand(`docker build -t ${imageName} .`);
}

function dockerLogin() {
    console.log('登陆镜像仓库');
    const region = 'ap-northeast-1';
    const instanceId = 'cri-azy285s79zw3ti5v';
    const version = '2018-12-01';
    const command = `aliyun cr GetAuthorizationToken --profile prod --region ${region} --InstanceId ${instanceId} --version ${version} --force`;
    const output = execSync(command, { encoding: 'utf8' });
    const result = JSON.parse(output);
    const password = result.AuthorizationToken.replace(/"/g, '');
    executeCommand(`docker login --username=cr_temp_user --password=${password} ${url}`)
}

function dockerTag() {
    console.log('标记镜像');
    executeCommand(`docker tag ${imageName} ${repositories}:${tag}`);
}

function dockerPush() {
    console.log('推送镜像');
    executeCommand(`docker push ${repositories}:${tag}`);
}

if (!imageName) return console.error('imageName is null');
if (!tag) return console.error('tag is null');

buildImage();
dockerLogin();
dockerTag();
dockerPush();
