#!/usr/bin/ruby

require 'json'
require 'optparse'

require 'debci'

$all = false
$json = false
$status_file = false
$field = 'status'

optparse = OptionParser.new do |opts|

  opts.banner = 'Usage: debci status [OPTIONS] [PACKAGE]'
  opts.separator 'Options:'

  opts.on('-a ARCH', '--arch ARCH', 'Sets architecture to act on') do |arch|
    Debci.config!(arch: arch)
  end

  opts.on('-s SUITE', '--suite SUITE', 'Sets suite to act on') do |suite|
    Debci.config!(suite: suite)
  end

  opts.on('-l', '--all', 'show status for all packages') do
    $all = true
  end

  opts.on('j', '--json', 'outputs JSON') do
    $json = true
  end

  opts.on('--status-file', 'outputs the full status file (implies --json)') do
    $status_file = true
    $json = true
  end

  opts.on('-f FIELD', '--field FIELD', 'displays FIELD from the status file (default: status)') do |f|
    $field = f
  end

end
optparse.parse!

if !$all && ARGV.size == 0
  puts "debci-status: when not using -l/--all, one or more PACKAGEs have to be specified."
  exit 1
end

def get_status_file(pkg)
  # FIXME duplicates logic found elsewhere :-/
  prefix = pkg.sub(/^((lib)?.).*/, '\1')
  File.join(Debci.config.packages_dir, prefix, pkg, 'latest.json')
end

def read_status_file(pkg)
  status_file = get_status_file(pkg)
  if File.exist?(status_file)
    JSON.load(File.open(status_file))
  else
    { 'package' => pkg, $field => nil }
  end
end

if $all
  packages = `debci-list-packages`.split
else
  packages = ARGV
end

def format_field(v)
  v || 'unknown'
end

if $json
  if packages.size == 1
    if $status_file
      puts File.read(get_status_file(packages.first))
    else
      data = read_status_file(packages.first)
      puts data[$field].to_json
    end
    exit
  end

  puts "["
  sep = nil
  packages.each do |p|
    entry = read_status_file(p)
    if entry && entry['status']
      puts sep if sep
      puts JSON.pretty_generate(entry, indent: '  ')
      sep = '  ,'
    end
  end
  puts "]"
else
  results = packages.map do |p|
    read_status_file(p)
  end
  results.reject! { |pkg| pkg.nil? }
  if !$all && results.size == 1
    puts format_field(results.first[$field])
  else
    max_length = results.map { |pkg| pkg['package'].length }.max
    fmt = "%-#{max_length}s %s"
    results.each do |pkg|
      puts fmt % [pkg['package'], format_field(pkg[$field])]
    end
  end
end
