import { spawnSync } from 'node:child_process';
import { existsSync } from 'node:fs';
import { chromium } from 'playwright';

const isLinux = process.platform === 'linux';

if (!isLinux) {
  process.exit(0);
}

const executablePath = chromium.executablePath();
let needsInstall = !existsSync(executablePath);

if (!needsInstall) {
  const ldd = spawnSync('ldd', [executablePath], { encoding: 'utf8' });
  const output = `${ldd.stdout ?? ''}${ldd.stderr ?? ''}`;
  needsInstall = ldd.status !== 0 || output.includes('not found');
}

if (!needsInstall) {
  process.exit(0);
}

const result = spawnSync('playwright', ['install', '--with-deps', 'chromium'], {
  stdio: 'inherit',
});

if (result.error) {
  throw result.error;
}

process.exit(result.status ?? 1);
