// cell clone <origin> <path>
// Clones a cell package <origin> to the local <path>, and links it.

var shop = use('internal/shop')
var link = use('link')
var fd = use('fd')
var http = use('http')

var run = function() {
  if (length(args) < 2) {
    log.console("Usage: cell clone <origin> <path>")
    log.console("Clones a cell package to a local path and links it.")
    return
  }

var origin = args[0]
var target_path = args[1]

// Resolve target path to absolute
target_path = shop.resolve_locator(target_path)

// Check if target already exists
  if (fd.is_dir(target_path)) {
    log.console("Error: " + target_path + " already exists")
    return
  }

log.console("Cloning " + origin + " to " + target_path + "...")

// Get the latest commit
var info = shop.resolve_package_info(origin)
  if (!info || info == 'local') {
    log.console("Error: " + origin + " is not a remote package")
    return
  }

// Update to get the commit hash
var update_result = shop.update(origin)
  if (!update_result) {
    log.console("Error: Could not fetch " + origin)
    return
  }

// Fetch and extract to the target path
var lock = shop.load_lock()
var entry = lock[origin]
  if (!entry || !entry.commit) {
    log.console("Error: No commit found for " + origin)
    return
  }

var download_url = shop.get_download_url(origin, entry.commit)
log.console("Downloading from " + download_url)

var _clone = function() {
  var zip_blob = http.fetch(download_url)
  shop.install_zip(zip_blob, target_path)

  log.console("Extracted to " + target_path)

  // Link the origin to the cloned path
  link.add(origin, target_path, shop)
  log.console("Linked " + origin + " -> " + target_path)
} disruption {
  log.console("Error during clone")
}
  _clone()
}
run()

$stop()
