text: "use strict";
  Object.defineProperty(exports, "__esModule", { value: true });
  exports.run = void 0;
  const utils_fs_1 = require("@ionic/utils-fs");
  const Debug = require("debug");
  const fs_1 = require("fs");
  const path = require("path");
  const errors_1 = require("../errors");
  const cli_1 = require("../utils/cli");
  const app_1 = require("./utils/app");
  const device_1 = require("./utils/device");
  const simulator_1 = require("./utils/simulator");
  const debug = Debug('native-run:ios:run');
  async function run(args) {
      let appPath = cli_1.getOptionValue(args, '--app');
      if (!appPath) {
          throw new errors_1.CLIException('--app is required', errors_1.ERR_BAD_INPUT);
      }
      const udid = cli_1.getOptionValue(args, '--target');
      const preferSimulator = args.includes('--virtual');
      const waitForApp = args.includes('--connect');
      const isIPA = appPath.endsWith('.ipa');
      if (!fs_1.existsSync(appPath)) {
          throw new errors_1.IOSRunException(`Path '${appPath}' not found`);
      }
      try {
          if (isIPA) {
              const { tmpdir } = await Promise.resolve().then(() => require('os'));
              const tempDir = fs_1.mkdtempSync(`${tmpdir()}${path.sep}`);
              debug(`Unzipping .ipa to ${tempDir}`);
              const appDir = await app_1.unzipIPA(appPath, tempDir);
              appPath = path.join(tempDir, appDir);
          }
          const bundleId = await app_1.getBundleId(appPath);
          const [devices, simulators] = await Promise.all([
              device_1.getConnectedDevices(),
              simulator_1.getSimulators(),
          ]);
          // try to run on device or simulator with udid
          if (udid) {
              if (devices.find(d => d.UniqueDeviceID === udid)) {
                  await device_1.runOnDevice(udid, appPath, bundleId, waitForApp);
              }
              else if (simulators.find(s => s.udid === udid)) {
                  await simulator_1.runOnSimulator(udid, appPath, bundleId, waitForApp);
              }
              else {
                  throw new errors_1.IOSRunException(`No device or simulator with UDID "${udid}" found`, errors_1.ERR_TARGET_NOT_FOUND);
              }
          }
          else if (devices.length && !preferSimulator) {
              // no udid, use first connected device
              await device_1.runOnDevice(devices[0].UniqueDeviceID, appPath, bundleId, waitForApp);
          }
          else {
              // use default sim
              await simulator_1.runOnSimulator(simulators[simulators.length - 1].udid, appPath, bundleId, waitForApp);
          }
      }
      finally {
          if (isIPA) {
              try {
                  await utils_fs_1.remove(appPath);
              }
              catch {
                  // ignore
              }
          }
      }
  }
  exports.run = run;
  