// cell install <locator> - Install a package and its dependencies
//
// Usage:
//   cell install <locator>   Install a package and its dependencies
//   cell install .           Install current directory package
//
// Options:
//   --target <triple>   Build for target platform
//   --dry-run           Show what would be installed
//   -r                  Recursively find and install all packages in directory

var shop = use('internal/shop')
var pkg = use('package')
var fd = use('fd')

var locator = null
var target_triple = null
var dry_run = false
var recursive = false
var i = 0
var locators = null
var cwd = fd.realpath('.')
var lock = null
var installed = 0
var failed = 0

var run = function() {
  for (i = 0; i < length(args); i++) {
    if (args[i] == '--target' || args[i] == '-t') {
      if (i + 1 < length(args)) {
        target_triple = args[++i]
      } else {
        log.error('--target requires a triple')
        return
      }
    } else if (args[i] == '--dry-run') {
      dry_run = true
    } else if (args[i] == '-r') {
      recursive = true
    } else if (args[i] == '--help' || args[i] == '-h') {
      log.console("Usage: cell install <locator> [options]")
      log.console("")
      log.console("Install a package and its dependencies.")
      log.console("")
      log.console("Options:")
      log.console("  --target <triple>  Build for target platform")
      log.console("  --dry-run          Show what would be installed")
      log.console("  -r                 Recursively find and install all packages in directory")
      return
    } else if (!starts_with(args[i], '-')) {
      locator = args[i]
    }
  }

  if (!locator && !recursive) {
    log.console("Usage: cell install <locator> [options]")
    return
  }

if (locator)
  locator = shop.resolve_locator(locator)

// Recursive mode: find all packages in directory and install each
if (recursive) {
  if (!locator) locator = '.'
  locator = shop.resolve_locator(locator)
  if (!fd.is_dir(locator)) {
    log.error(`${locator} is not a directory`)
    return
  }
  locators = filter(pkg.find_packages(locator), function(p) {
    return p != cwd
  })
  if (length(locators) == 0) {
    log.console("No packages found in " + locator)
    return
  }
  log.console(`Found ${text(length(locators))} package(s) in ${locator}`)

  if (dry_run) {
    log.console("Would install:")
    arrfor(locators, function(loc) {
      lock = shop.load_lock()
      log.console("  " + loc + (lock[loc] ? " (already installed)" : ""))
    })
  } else {
    installed = 0
    failed = 0
    arrfor(locators, function(loc) {
      log.console("  Installing " + loc + "...")
      var _inst = function() {
        shop.sync(loc, {target: target_triple})
        installed = installed + 1
      } disruption {
        failed = failed + 1
        log.console(`  Warning: Failed to install ${loc}`)
      }
      _inst()
    })

    log.console("Installed " + text(installed) + " package(s)." + (failed > 0 ? " Failed: " + text(failed) + "." : ""))
  }
  return
}

  // Single package install with dependencies
  if (dry_run) {
    log.console("Would install: " + locator + " (and dependencies)")
    return
  }

  log.console("Installing " + locator + "...")
  shop.sync_with_deps(locator, {refresh: true, target: target_triple})
  log.console("Done.")
}
run()

$stop()
