#!/bin/bash

all=false
short=false
uid="$UID"
help=false

eval set -- $(getopt -n afm-util -s bash -l all,help,short,uid: -o ahsu: -- "$@")
while :
do
  case "$1" in
  -a|--all) all=true; shift;;
  -h|--help) help=true; shift;;
  -s|--short) short=true; shift;;
  -u|--uid) uid="$2"; shift 2;;
  --) shift; break;;
  *) help=true; break;;
  esac
done

[[ "$1" = help ]] && help=true
if $help
then
  cat << EOC

usage: $(basename $0) [-u UID] CMD [arg]

The command CMD is of of the below commands:

  list
  runnables      list the runnable widgets installed
                 option -a or --all for all instances
                 option -s or --short for a synthetic output

  info id
  detail id      print detail about the installed widget of id

  ps
  runners        list the running instance
                 option -a or --all for all instances
                 option -s or --short for a synthetic output

  run id
  start id       start an instance of the widget of id

  once id        run once an instance of the widget of id

  kill rid
  terminate rid  terminate the running instance rid

  status rid
  state rid      get status of the running instance rid

EOC
  exit 0
fi

send() {
  local verb="$1"
  afb-client -u afm-util -H -d unix:/run/platform/apis/ws/afm-main "$verb" "$2" |
  awk '$1=="ON-REPLY" && $3!="success"{$1="ERROR:";$2="";print > "/dev/stderr";exit 1;}NR>1'
}

show() {
  if $short && [[ -n "$(type -p jq)" ]]
  then
    jq -r "$1" | sort -n
  else
    cat
  fi
}

case "$1" in

  list|runnables)
    send runnables "{\"all\":$all,\"uid\":$uid}" |
    show '.[]|@text "\(.id)\t\(.description)"'
    ;;

  info|detail)
    i=$2
    send detail "{\"id\":\"$i\",\"uid\":$uid}"
    ;;

  ps|runners)
    send runners  "{\"all\":$all,\"uid\":$uid}" |
    show '.[]|@text "\(.runid)\t\(.id)"'
    ;;

  run|start)
    i=$2
    send start "{\"id\":\"$i\",\"uid\":$uid}"
    ;;

  once)
    i=$2
    send once "{\"id\":\"$i\",\"uid\":$uid}"
    ;;

  terminate|kill)
    i=$2
    if echo -n "$i" | grep -q '^[0-9]\{1,\}$'
    then
      send terminate  "{\"runid\":$i,\"uid\":$uid}"
    else
      send terminate  "{\"id\":\"$i\",\"uid\":$uid}"
    fi
    ;;

  state|status)
    i=$2
    if echo -n "$i" | grep -q '^[0-9]\{1,\}$'
    then
      send state  "{\"runid\":$i,\"uid\":$uid}"
    else
      send state  "{\"id\":\"$i\",\"uid\":$uid}"
    fi
    ;;

  *)
    echo "unknown command $1" >&2
    exit 1
    ;;
esac
