import { logger } from './logger';
import { Spawner } from './spawner';
import { stringifyError } from './stringify-error';

export async function getL4TVersion(props: {
  spawner: Spawner;
}): Promise<string | null> {
  const { spawner } = props;
  let l4tInfo = '';
  try {
    // These steps are the equivalent of running:
    // `dpkg -l | grep 'nvidia-l4t-core' | awk '{print $3}'`
    const packages = await spawner.run({
      exe: 'dpkg',
      args: ['-l']
    });
    const packageArr = packages.split('\n');
    for (const p of packageArr) {
      // l4tInfo is in the form:
      // `ii  nvidia-l4t-core  35.2.1-20230124153320  arm64  NVIDIA Core Package`
      if (p.includes('nvidia-l4t-core')) {
        const details = p.split(/\s+/);
        l4tInfo = details[2];
      }
    }
  } catch (err) {
    logger.error(stringifyError(err));
  }
  logger.debug(l4tInfo);
  const re = RegExp('([0-9]+.[0-9]+(.[0-9]+)?).*', 'g');
  const found = re.exec(l4tInfo.trim());
  logger.debug(found);
  let l4tVersion: null | string = null;
  if (found && found.length >= 2) {
    // Group 1 contains the L4T version string
    l4tVersion = found[1];
  }
  return l4tVersion;
}
