#!/usr/bin/bash


# Must specify a JSON with a following structure:

ENDPOINT="http://localhost:8087"
if [[ $DOCKER_ENVIRONMENT ]]; then
  ENDPOINT="http://oc-catalog:8087"
fi

if [[ $DOCKER_ENDPOINT ]]; then
  ENDPOINT="$DOCKER_ENDPOINT"
fi

[[ -z $1 ]] && { echo "Must specify a json path"; exit 1; }
[[ ! -f $1 ]] && { echo "$1 is not a file"; exit 1; }
cat "$1" | jq empty  || { echo "$1 is not a valid JSON"; exit 1; }

########

while read row; do
    TRGT_ENDPOINT=$(echo $row | jq -r '.api')

    while read item; do
      echo `echo $item | jq -r '.name'` to $ENDPOINT${TRGT_ENDPOINT}
      answer=$(curl --fail "$ENDPOINT${TRGT_ENDPOINT}" \
        -X POST \
        -H "Content-Type: application/json" \
        -d "$item")
      echo $answer
      if [[ $? -ne 0 || "$answer" == *"<html>"*  ]]; then
        exit 1
      fi
    done < <(echo "$row" | jq -c '.content[]')
done < <(jq -c '.[]' $1)


echo
echo
echo
echo "All models submitted correctly!"
