#!/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`"

WHEN=""
TO=""
ERR=0
ENV=""

while [ $# -gt 0 ] ; do
  if [ "$1" = "--last" ] ; then
# --last #sec
    WHEN="$1 $2"
    shift
  elif [ "$1" = "--since" ] ; then
# --since simple local 24h time eg. 2130
    WHEN="$1 $2"
    shift
  elif [ "$1" = "--root" ] ; then
# support for developers
    root="$2"
    shift
  elif [ "$1" = "--to" ] ;then
# where it all goes
    TO="$2"
    shift
  elif [ "$1" = "--profile" ] ; then
    AWS_PROFILE="$2"
    export AWS_PROFILE
    shift
  elif [ "$1" = "--env" ] ; then
    ENV="$2"
    shift
  else
    echo "unrecognized option $1"
    ERR=1
  fi
  shift
done

if [ -z "$WHEN" ] ; then
  echo "some starting point required"
  ERR=1
fi

if [ -z "$TO" ] ; then
  echo "must specify --to directory"
  ERR=1
fi

if [ -f "$TO" ] ; then
  echo "$TO must be a directory"
  ERR=1
fi

if [ -z "$ENV" ] ; then
  echo "must specify an environment with --env"
  ERR=1
fi

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

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

set -x

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.cloudwatchreader.Main --zip /tmp/logs-captured.zip --env "$ENV" $WHEN

if [ -d "$TO" ] ; then
  rm -f "$TO"/*
else
  mkdir "$TO"
fi
cd $TO
unzip /tmp/logs-captured


