import { CliLeaf, CliBranch, CliTerseError } from '@alwaysai/alwayscli';
import { checkForDockerComponent } from '../components/docker';
import { checkUserIsLoggedInComponent } from '../components/user';
import { ALWAYSAI_OS_PLATFORM } from '../environment';
import { JsSpawner } from '../util';
import { runDockerContainerForeground } from '../util/docker/docker-cmd';

const installPcieDriver = CliLeaf({
  name: 'install-pcie-driver',
  description: 'Install the Hailo PCIe drivers',
  async action(_) {
    if (ALWAYSAI_OS_PLATFORM !== 'linux') {
      throw new CliTerseError('Hailo is supported only on Linux systems.');
    }
    await checkUserIsLoggedInComponent({ yes: false });
    await checkForDockerComponent();
    const spawner = JsSpawner();
    const hailoDockerfile = 'alwaysai/edgeiq-qa:hailo-amd64-latest';
    await runDockerContainerForeground({
      targetHostSpawner: spawner,
      cmd: {
        dockerImageId: hailoDockerfile,
        remove: true,
        pullImage: true,
        volumes: [
          '/lib/modules:/lib/modules',
          '/lib/firmware:/lib/firmware',
          '/lib/udev:/lib/udev',
          '/usr/src:/usr/src',
          '/dev:/dev'
        ],
        exe: '/bin/bash',
        exeArgs: ['-c', './install.sh --pcie-driver-only']
      }
    });
  }
});

const uninstallPcieDriver = CliLeaf({
  name: 'uninstall-pcie-driver',
  description: 'Uninstall the Hailo PCIe drivers',
  async action(_) {
    await checkForDockerComponent();
    const spawner = JsSpawner();
    const hailoDockerfile = 'alwaysai/edgeiq-qa:hailo-amd64-latest';
    await runDockerContainerForeground({
      targetHostSpawner: spawner,
      cmd: {
        dockerImageId: hailoDockerfile,
        remove: true,
        pullImage: true,
        volumes: [
          '/lib/modules:/lib/modules',
          '/lib/firmware:/lib/firmware',
          '/lib/udev:/lib/udev',
          '/usr/src:/usr/src',
          '/dev:/dev'
        ],
        exe: '/bin/bash',
        exeArgs: ['-c', './uninstall.sh']
      }
    });
  }
});

export const hailo = CliBranch({
  name: 'hailo',
  description: `Install or uninstall the Hailo PCIe drivers.`,
  subcommands: [installPcieDriver, uninstallPcieDriver]
});
