#!/bin/bash -e

# This assumes that a FLAS+Ziniki package has been downloaded and this script is $ZINIKI_ROOT/bin/ziniki
root="`dirname $0`"
root="`dirname $root`"

MODE=""
SORT=""
INDOMAIN=""
IDENTITY=""
CRED=""
ERR=0

while [ $# -gt 0 ] ; do
  if [ "$1" = "--profile" ] ; then
    AWS_PROFILE="$2"
    export AWS_PROFILE
    shift
  elif [ "$1" = "--all" ] ; then
    MODE="$1"
    SORT=true
  elif [ "$1" = "--app" ] ; then
    MODE="$1 $2"
    shift
  elif [ "$1" = "--apps" ] ; then
    MODE="$1"
  elif [ "$1" = "--assemblies" ] ; then
    MODE="$1"
  elif [ "$1" = "--assembly" ] ; then
    MODE="$1 $2"
    shift
  elif [ "$1" = "--domains" ] ; then
    MODE="$1"
  elif [ "$1" = "--identities" ] ; then
    MODE="$1"
  elif [ "$1" = "--show" ] ; then
    MODE="$1 $2"
    shift
  elif [ "$1" = "--tokens" ] ; then
    MODE="$1"
  elif [ "$1" = "--users" ] ; then
    MODE="$1"
  elif [ "$1" = "--indomain" ] ; then
    INDOMAIN="--indomain $2"
    shift
  elif [ "$1" = "--identity" ] ; then
    IDENTITY="--identity $2"
    shift
  elif [ "$1" = "--cred" ] ; then
    IDENTITY="--cred $2"
    shift
  else
    echo "unrecognized option $1"
    ERR=1
  fi
  shift
done

if [ -z "$AWS_PROFILE" ] ; then
  echo "AWS_PROFILE or --profile required"
  ERR=1
fi

if [ "$ERR" = 1 ] ; then
  exit 1
fi

runit() {
  java \
    -Djdk.tls.client.protocols=TLSv1.2 \
    -Dui4j.headless=true \
    -Dglass.platform=Monocle \
    -Dmonocle.platform=Headless \
    -Dprism.order=sw \
    -Dziniki.disable.openid.certs=disable \
    $JAVAOPTS \
    -cp "$root"/'lib/*' \
  org.ziniki.tools.dynamoreader.Main "$@"
}

if [ "$SORT" = "true" ] ; then
  runit $MODE | sort
else
  runit $MODE $INDOMAIN $IDENTITY $CRED
fi
exit $?
