1import fs from 'fs';
2import path from 'path';
3
4import gradleScript from './EasBuildGradleScript';
5import * as Paths from './Paths';
6
7const APPLY_EAS_GRADLE = 'apply from: "./eas-build.gradle"';
8
9function hasApplyLine(content: string, applyLine: string): boolean {
10  return (
11    content
12      .replace(/\r\n/g, '\n')
13      .split('\n')
14      // Check for both single and double quotes
15      .some((line) => line === applyLine || line === applyLine.replace(/"/g, "'"))
16  );
17}
18
19export function getEasBuildGradlePath(projectRoot: string): string {
20  return path.join(projectRoot, 'android', 'app', 'eas-build.gradle');
21}
22
23export async function configureEasBuildAsync(projectRoot: string): Promise<void> {
24  const buildGradlePath = Paths.getAppBuildGradleFilePath(projectRoot);
25  const easGradlePath = getEasBuildGradlePath(projectRoot);
26
27  await fs.promises.writeFile(easGradlePath, gradleScript);
28
29  const buildGradleContent = await fs.promises.readFile(path.join(buildGradlePath), 'utf8');
30
31  const hasEasGradleApply = hasApplyLine(buildGradleContent, APPLY_EAS_GRADLE);
32
33  if (!hasEasGradleApply) {
34    await fs.promises.writeFile(
35      buildGradlePath,
36      `${buildGradleContent.trim()}\n${APPLY_EAS_GRADLE}\n`
37    );
38  }
39}
40
41export async function isEasBuildGradleConfiguredAsync(projectRoot: string): Promise<boolean> {
42  const buildGradlePath = Paths.getAppBuildGradleFilePath(projectRoot);
43  const easGradlePath = getEasBuildGradlePath(projectRoot);
44
45  const hasEasGradleFile = await fs.existsSync(easGradlePath);
46
47  const buildGradleContent = await fs.promises.readFile(path.join(buildGradlePath), 'utf8');
48  const hasEasGradleApply = hasApplyLine(buildGradleContent, APPLY_EAS_GRADLE);
49
50  return hasEasGradleApply && hasEasGradleFile;
51}
52