#!/usr/bin/env bash

PATH=.:/sbin:/usr/sbin:/bin:/usr/bin:/usr/local/bin:`dirname $0`

target=''

usage() {
  echo 'Usage: prune_workers -t target'
  echo
  echo "Options:"
  echo "  -h: this help."
  echo "  -t: target name."
  echo
}

ARGS="$@"
# Validation
while getopts 't:h' OPT; do
  case $OPT in
    't' )
      target=$OPTARG
      ;;
    'h' )
      usage
      exit 0
      ;;
    '?' )
      usage
      exit 1
      ;;
  esac
done

shift $((OPTIND - 1))

if [ $# != 0 ]; then
  usage
  exit 1
fi

if [ -z $target ]; then
  usage
  exit 1
fi

fly -t $target ws | awk '$6=="stalled" {print $1}' | xargs -t -n 1 --no-run-if-empty fly -t $target prune-worker -w
