#!/bin/sh

set -eu

short_options='jlf:s'
long_options='json,all,field:,status-file'

usage() {
  cat <<EOF
usage: debci-status [OPTIONS] [PACKAGE] [PACKAGE ...]

When not using -l/--all, one or more PACKAGEs have to be specified.

Options:

  -l, -all                  show status for all packages
  -j, --json                output JSON
  --status-file         outputs the full status file (implies --json)
  -f FIELD, --field FIELD   display FIELD from the status file (default: status)

$@
EOF
}

base=$(readlink -f $(dirname $(readlink -f $0))/..)
cd $base
. $base/lib/environment.sh
. $base/lib/functions.sh


get_status_file() {
  local pkg="$1"
  local status_dir=$(status_dir_for_package "$1")
  echo "${status_dir}/latest.json"
}

get_status() {
  local pkg="$1"
  local length="${2:-0}"

  local status_file=$(get_status_file "$pkg")

  if [ -f "$status_file" ]; then
    ruby -e "
      field = \"$field\"
      length = $length
      json = $json"'
      require "json"
      data = JSON.parse(ARGF.read)
      value = data[field] || "unknown"
      if json
        value = value.to_json
      end
      if length > 0
        printf("%-#{length}s ", data["package"])
      end
      puts(value)
      ' "$status_file"
  else
    if [ "$length" -eq 0 ]; then
      echo "unknown"
    else
      printf "%-${length}s unknown\n" "$pkg"
    fi
  fi
}

# defaults
all=''
json='false'
field='status'
status_file=''

while true; do
  case "$1" in
    --json|-j)
      json='true'
      shift
      ;;
    --all|-l)
      all=true
      shift
      ;;
    --field|-f)
      field="$2"
      shift 2
      ;;
    --status-file)
      status_file='true'
      json='true'
      shift
      ;;
    --)
      shift
      break
      ;;
    *)
      shift
      ;;
  esac
done

if [ $all ]; then
  pkgs=$(debci-list-packages)
  eval set -- $pkgs
fi

if [ $# -lt 1 ]; then
  usage
  exit 1
fi

# JSON data
indent='cat'
if [ $status_file ]; then
  if [ $# -gt 1 -o $all ]; then
    echo "["
    indent=indent
  fi
  prefix=''
  for pkg in $@; do
    status_file=$(get_status_file "$pkg")
    if [ -f "$status_file" ]; then
      (
        echo "$prefix"
        cat "$status_file"
      ) | $indent
      prefix=','
    fi
  done
  [ $# -gt 1 -o $all ] && echo "]"
  exit
fi

# single package
if [ $# -eq 1 -a ! $all ]; then
  get_status "$1"
  exit
fi

# multiple packages
max_length=$(for pkg in $@; do echo "$pkg"; done | wc -L)
for pkg in $@; do
  get_status "$pkg" "$max_length"
done
