#!/bin/bash

#
# Generates random valid UUID
#
generate_uuid() {
    local N B C='89ab'
    local RES=''
    for (( N=0; N < 16; ++N )) do
        B=$(( $RANDOM % 256 ))

        case $N in
            6)
                RES="${RES}$(printf '4%x' $(( B % 16 )))"
                ;;
            8)
                RES="${RES}$(printf '%c%x' ${C:$RANDOM%${#C}:1} $(( B % 16 )))"
                ;;
            3 | 5 | 7 | 9)
                RES="${RES}$(printf '%02x-' $B)"
                ;;
            *)
                RES="${RES}$(printf '%02x' $B)"
                ;;
        esac
    done
    echo -n $RES
}

#
# Extract document_id (if present) and HTTP response code from curl response passed as argument
#
extract_document_id() {
  DOCUMENT_ID=$(echo $1 | grep document_id | tail -1 | sed -e 's/^.*"document_id": *"\([^"]*\)".*$/\1/')
  HTTP_RETURN_CODE=$(echo echo $1 | tail -1 | sed -e 's/^.*\([0-9][0-9][0-9]\)$/\1/')
}

# Helper function to make curl requests
make_request() {
    local method=$1
    local endpoint=$2
    local data=$3
    local headers=$4
    if [ "xx${headers}" == "xx" ]; then
      headers='-H "Content-Type: application/json"'
    fi
    # echo "Testing $method $endpoint"
    # echo "Request data: $data"
    # echo "Request headers: $headers"
    CMD="curl -X $method \"$API_BASE$endpoint\" -s  -w \"\n%{http_code}\" -H \"Authorization: Bearer $AUTH_TOKEN\" $headers $data"
    echo $CMD
    RES=$(eval $CMD 2>/dev/null)
    echo "Response: [${RES}]"
    extract_document_id "$RES"
    # echo "document_id --> ${DOCUMENT_ID}"
    if [[ ${HTTP_RETURN_CODE} -lt 300 ]]; then
      echo "SUCCESS. code = ${HTTP_RETURN_CODE}"
    else
      echo "ERROR. code = ${HTTP_RETURN_CODE}"
    fi
    echo -e "\n\n"
    if [ "${EXECUTE_ALL}" != "-a" ]; then
      echo "Press any key to continue..."
      read -n 1 -s -r
      echo -e "\n\n"
    fi
}

#
# Simple scanner of cmd line arguments, inferring meaning of the value
# It recognized:
#  a)  host URL (starts with 'http' prefix)
#  b)  JWT token (starts with 'ey' prefix)
#  c)  flag -a  to execute all tests w/o waiting for user pressing any key
#
while [ $# -gt 0 ]; do
    echo "Argument: [${1}]"
    if [[ "$1" == ey* ]]; then
      AUTH_TOKEN=$1
    fi
    if [[ "$1" == http* ]]; then
      HOST=$1
    fi
    if [[ "$1" == "-a" ]]; then
      EXECUTE_ALL=$1
    fi
    shift  # Removes $1 and shifts remaining args left
done


if [ "xx${HOST}" == "xx" ]; then
  HOST="http://localhost:7272"
fi
API_BASE="$HOST/v3"
# Once integrated with CleverMicro, token can be obtained from CleverMicro
# if [ "xx${AUTH_TOKEN}" == "xx" ]; then
#  AUTH_TOKEN=$(curl $HOST/api/v0/login -s -d '{"username":"hugo@cleverthis.com","password":"tellmeall"}' -H "Content-Type: application/json" | sed -e "s/.*access_token...\(.*\)..$/\1/")
# fi
