import { OpResult, logger } from 'mslib'
const util = require('util');
const cipro = require('child_process');
const exec = util.promisify(cipro.exec);
const execFile = util.promisify(cipro.execFile);


export class ShellUtils {

    /**
     * 执行shell指令
     */
    static async exec(cmd: string): Promise<OpResult<ShellOut>> {
        logger.trace('准备执行shell指令----[%s]', cmd)
        try {
            const { stdout, stderr } = await exec(cmd).catch(e => {
                logger.error(`准备执行shell指令发生异常[${cmd}]`, e)
                return Promise.reject(e)
            });
            const out: ShellOut = {
                stdout,
                stderr
            }
            return OpResult.success('OK', out)
        } catch (e) {
            return OpResult.error(e + '')
        }
    }

    /**
    * 执行shell脚本
    */
    static async execFile(filePath: string, args: ReadonlyArray<string> | undefined | null): Promise<OpResult<ShellOut>> {
        logger.trace('准备执行shell脚本----[%s]', filePath)
        try {
            const { stdout, stderr } = await execFile(filePath, args).catch(e => {
                logger.error(`准备执行shell脚本发生异常[${filePath}]`, e)
                return Promise.reject(e)
            });
            const out: ShellOut = {
                stdout,
                stderr
            }
            return OpResult.success('OK', out)
        } catch (e) {
            return OpResult.error(e + '')
        }
    }


}

export interface ShellOut {
    stdout?: string
    stderr?: string
}