import rimraf from 'rimraf';

import { DOCKERFILE_STANDALONE, DOCKERFILE } from '../../paths';
import { JsSpawner } from '../../util';
import { AppJsonFile } from './app-json-file';

export async function writeStandaloneDockerfile() {
  const spawner = JsSpawner();
  if (!(await spawner.exists(DOCKERFILE))) {
    throw new Error(`${DOCKERFILE} does not exist!`);
  }
  if (await spawner.exists(DOCKERFILE_STANDALONE)) {
    await rimraf(DOCKERFILE_STANDALONE);
  }
  const dockerfileContents: string[] = [];
  dockerfileContents.push(
    '# Do not edit this file; auto-generated by alwaysAI'
  );
  const origContents = await spawner.readFile(DOCKERFILE);
  origContents.split(/\r?\n/).forEach((line) => {
    dockerfileContents.push(line);
  });
  dockerfileContents.push('ENV PATH="/app/venv/bin:$PATH"');
  dockerfileContents.push('ENV PYTHONUNBUFFERED=1');
  dockerfileContents.push('WORKDIR /app');
  dockerfileContents.push('COPY . ./');
  const appJsonFile = AppJsonFile();
  const appJson = appJsonFile.read();
  const startScript = `CMD ["${appJson.scripts.start
    .split(' ')
    .join('", "')}"]`;
  dockerfileContents.push(startScript);
  await spawner.writeFile(DOCKERFILE_STANDALONE, dockerfileContents.join('\n'));
}
