#!/bin/bash
# vim: ts=4:sw=4

declare -a CURL_PARAMS

usage() {
	echo "Usage: $0 [-n] [-v] [-u username:password] [-j jwt-token] urlbase [schema-file]*"
	echo ""
	echo "    -v   verbose (passed to the curl tool)"
	echo "    -n   dry run (only version 3.x and higher!)"
	echo "    -u   use HTTP Basic authorization (the argument is just passed to the curl tool)"
	echo "    -j   use JWT authorization (Authorization: Bearer header is added)"
	echo "         if the argument starts with @, the rest is treated as a file that contains the token"
	echo ""
}

DRY=false

while getopts "vu:j:Fn" o; do
	case "${o}" in
		u)
			CURL_PARAMS+=("-u" "${OPTARG}")
			;;
		v)
			CURL_PARAMS+=("-v")
			;;
		n)
			DRY=true
			;;
		F)
			DRY=false
			;;
		j)
			if [[ "${OPTARG}" == @* ]]; then
				set -e
				TOKENFILE="${OPTARG#@}"
				read TOKEN <"$TOKENFILE"
				set +e
			else
				TOKEN="$OPTARG"
			fi
			CURL_PARAMS+=("-H" "Authorization: Bearer ${TOKEN}")
			;;
		*)
			usage
			exit 1
			;;
	esac
done
shift $((OPTIND-1))


URL_BASE="$1"

if [ -z "$URL_BASE" ]; then
	usage
	exit 1
fi
shift

# remove trailing slash, if any
URL_BASE="${URL_BASE%/}"

if curl -f -s "$URL_BASE"/entity >/dev/null ; then
	if curl -f "${CURL_PARAMS[@]}" -s "$URL_BASE"/schema -o /dev/null ; then
		true;
	else
		echo "failed to list schemas; probably authorization error"
		exit 1
	fi
else
	echo "invalid URL; does not point to HWCMS: $URL_BASE"
	exit 1
fi

if [ -z "$*" ]; then
  # no filenames
  exit 0
fi

QP="dry=$DRY"

if [[ "$0" == *mass.sh || "$0" == *multi.sh ]]; then
    declare -a PARTS
    for schemafile in "$@" ; do
        entity=$(basename "${schemafile}")
        entity=${entity%%.json}
        entity=${entity%%-schema}
        entity=${entity#[0-9]*-}
        PARTS+=("-F" "${entity}=@${schemafile}")
    done
    OUTPUT=$(curl -w "\nresponse: %{http_code} %{content_type}" -s "${CURL_PARAMS[@]}"  "$URL_BASE"/schema/"?$QP" "${PARTS[@]}")
    echo "$OUTPUT" | grep -v '^response'
    if (echo "$OUTPUT" | grep -q 'response: [^2]'); then
      echo "FAILED!"
      exit 1
    fi
else
    for schemafile in "$@" ; do
        entity=$(basename "${schemafile}")
        entity=${entity%%.json}
        entity=${entity%%-schema}
        entity=${entity#[0-9]*-}
        if curl -f "${CURL_PARAMS[@]}" -s "$URL_BASE"/schema/$entity"?$QP" >/dev/null; then
            echo Updating $entity
        else
            echo Creating $entity
        fi
        set -e
        cat "$schemafile" | curl -f -w "response: %{http_code} %{content_type}" -o /dev/null -s "${CURL_PARAMS[@]}"  "$URL_BASE"/schema/$entity -X PUT -H 'Content-Type: application/json' --data @-
        echo
        set +e

    done
fi
