import { execa } from 'execa';

import { env } from '../env';

export const runInJobContainer = async (args: {
  workdir: string;
  command: string[];
  environment: Record<string, string>;
  redact: (value: string) => string;
  timeoutMs: number;
}) => {
  const envArgs = Object.entries(args.environment).flatMap(([name, value]) => [
    '-e',
    `${name}=${value}`,
  ]);
  const networkArgs = env.network ? ['--network', env.network] : [];
  const result = await execa(
    'docker',
    [
      'run',
      '--rm',
      '--memory',
      '4g',
      '--cpus',
      '2',
      ...networkArgs,
      ...envArgs,
      '-v',
      `${args.workdir}:/workspace`,
      '-w',
      '/workspace/repo',
      env.jobImage,
      ...args.command,
    ],
    {
      all: true,
      reject: false,
      timeout: args.timeoutMs,
    },
  );
  return {
    exitCode: result.exitCode ?? 0,
    output: args.redact(result.all),
  };
};
