// cell remove <locator> - Remove a package from the shop
//
// Usage:
//   cell remove <locator>   Remove a package from the shop
//   cell remove .           Remove current directory package from shop
//
// Options:
//   --prune     Also remove packages no longer needed by any root
//   --dry-run   Show what would be removed

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

var target_pkg = null
var prune = false
var dry_run = false
var i = 0
var resolved = null

for (i = 0; i < length(args); i++) {
  if (args[i] == '--prune') {
    prune = true
  } else if (args[i] == '--dry-run') {
    dry_run = true
  } else if (args[i] == '--help' || args[i] == '-h') {
    log.console("Usage: cell remove <locator> [options]")
    log.console("")
    log.console("Remove a package from the shop.")
    log.console("")
    log.console("Options:")
    log.console("  --prune    Also remove packages no longer needed by any root")
    log.console("  --dry-run  Show what would be removed")
    $stop()
  } else if (!starts_with(args[i], '-')) {
    target_pkg = args[i]
  }
}

if (!target_pkg) {
  log.console("Usage: cell remove <locator> [options]")
  $stop()
}

// Resolve relative paths to absolute paths
if (target_pkg == '.' || starts_with(target_pkg, './') || starts_with(target_pkg, '../') || fd.is_dir(target_pkg)) {
  resolved = fd.realpath(target_pkg)
  if (resolved) {
    target_pkg = resolved
  }
}

var packages_to_remove = [target_pkg]

var lock = null
var all_packages = null
var needed = null
if (prune) {
  // Find packages no longer needed
  // Get all dependencies of remaining packages
  lock = shop.load_lock()
  all_packages = shop.list_packages()

  // Build set of all needed packages (excluding target)
  needed = {}
  arrfor(all_packages, function(p) {
    if (p == target_pkg || p == 'core') return

    // Mark this package and its deps as needed
    needed[p] = true
    var _gather = function() {
      var deps = pkg.gather_dependencies(p)
      arrfor(deps, function(dep) {
        needed[dep] = true
      })
    } disruption {
      // Skip if can't read deps
    }
    _gather()
  })

  // Find packages that are NOT needed
  arrfor(all_packages, function(p) {
    if (p == 'core') return
    if (!needed[p] && find(packages_to_remove, p) == null) {
      push(packages_to_remove, p)
    }
  })
}

if (dry_run) {
  log.console("Would remove:")
  arrfor(packages_to_remove, function(p) {
    log.console("  " + p)
  })
} else {
  arrfor(packages_to_remove, function(p) {
    // Remove any link for this package
    if (link.is_linked(p)) {
      link.remove(p)
    }

    // Remove from shop
    shop.remove(p)
  })

  log.console("Removed " + text(length(packages_to_remove)) + " package(s).")
}

$stop()
