// cell audit [<locator>] - Test-compile all .ce and .cm scripts
//
// Usage:
//   cell audit              Audit all packages
//   cell audit <locator>    Audit specific package
//   cell audit .            Audit current directory package
//
// Compiles every script in the package(s) to check for errors.
// Continues past failures and reports all issues at the end.

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

var target_package = null
var i = 0
var resolved = null

for (i = 0; i < length(args); i++) {
  if (args[i] == '--help' || args[i] == '-h') {
    log.console("Usage: cell audit [<locator>]")
    log.console("")
    log.console("Test-compile all .ce and .cm scripts in package(s).")
    log.console("Reports all errors without stopping at the first failure.")
    $stop()
  } else if (!starts_with(args[i], '-')) {
    target_package = args[i]
  }
}

// Resolve local paths
if (target_package) {
  if (target_package == '.' || starts_with(target_package, './') || starts_with(target_package, '../') || fd.is_dir(target_package)) {
    resolved = fd.realpath(target_package)
    if (resolved) {
      target_package = resolved
    }
  }
}

var packages = null
var total_ok = 0
var total_errors = 0
var total_scripts = 0
var all_failures = []

if (target_package) {
  packages = [target_package]
} else {
  packages = shop.list_packages()
}

arrfor(packages, function(p) {
  var scripts = shop.get_package_scripts(p)
  if (length(scripts) == 0) return

  log.console("Auditing " + p + " (" + text(length(scripts)) + " scripts)...")
  var result = shop.build_package_scripts(p)
  total_ok = total_ok + result.ok
  total_errors = total_errors + length(result.errors)
  total_scripts = total_scripts + result.total

  arrfor(result.errors, function(e) {
    push(all_failures, p + ": " + e)
  })
})

log.console("")
if (length(all_failures) > 0) {
  log.console("Failed scripts:")
  arrfor(all_failures, function(f) {
    log.console("  " + f)
  })
  log.console("")
}

log.console("Audit complete: " + text(total_ok) + "/" + text(total_scripts) + " scripts compiled" + (total_errors > 0 ? ", " + text(total_errors) + " failed" : ""))

$stop()
